LeetCode 题解工作台

统计平方和三元组的数目

一个 平方和三元组 (a,b,c) 指的是满足 a 2 + b 2 = c 2 的 整数 三元组 a , b 和 c 。 给你一个整数 n ,请你返回满足 1 的 平方和三元组 的数目。 示例 1: 输入: n = 5 输出: 2 解释: 平方和三元组为 (3,4,5) 和 (4,3,5) 。 示例…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数学·结合·enumeration

bolt

答案摘要

我们在 $[1, n)$ 的范围内枚举 和 ,然后计算 $c = \sqrt{a^2 + b^2}$,如果 是整数且 $c \leq n$,那么就找到了一个平方和三元组,答案加一。 枚举结束后,返回答案即可。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数学·结合·enumeration 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

一个 平方和三元组 (a,b,c) 指的是满足 a2 + b2 = c2 的 整数 三元组 ab 和 c 。

给你一个整数 n ,请你返回满足 1 <= a, b, c <= n 的 平方和三元组 的数目。

 

示例 1:

输入:n = 5
输出:2
解释:平方和三元组为 (3,4,5) 和 (4,3,5) 。

示例 2:

输入:n = 10
输出:4
解释:平方和三元组为 (3,4,5),(4,3,5),(6,8,10) 和 (8,6,10) 。

 

提示:

  • 1 <= n <= 250
lightbulb

解题思路

方法一:枚举

我们在 [1,n)[1, n) 的范围内枚举 aabb,然后计算 c=a2+b2c = \sqrt{a^2 + b^2},如果 cc 是整数且 cnc \leq n,那么就找到了一个平方和三元组,答案加一。

枚举结束后,返回答案即可。

时间复杂度 O(n2)O(n^2),其中 nn 是给定的整数。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
class Solution:
    def countTriples(self, n: int) -> int:
        ans = 0
        for a in range(1, n):
            for b in range(1, n):
                x = a * a + b * b
                c = int(sqrt(x))
                if c <= n and c * c == x:
                    ans += 1
        return ans
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    The candidate understands the concept of square triples and can break the problem into smaller, manageable parts.

  • question_mark

    The candidate demonstrates the ability to optimize brute force methods by applying mathematical properties.

  • question_mark

    The candidate shows attention to detail in ensuring that each valid pair is counted only once.

warning

常见陷阱

外企场景
  • error

    Failing to account for the fact that (a, b) and (b, a) represent the same triple, leading to double-counting.

  • error

    Neglecting to check that the square root of a² + b² is an integer and not just a floating-point value.

  • error

    Not handling the edge cases where n is small or large, leading to either incorrect answers or inefficient solutions.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Consider the problem for n up to a much larger value, e.g., 1000, and see how the solution needs to scale.

  • arrow_right_alt

    Modify the problem to only count distinct triples (a, b, c) without considering the order of a and b.

  • arrow_right_alt

    Extend the problem to check if a² + b² + c² = d² for four variables, increasing the complexity.

help

常见问题

外企场景

统计平方和三元组的数目题解:数学·结合·enumeration | LeetCode #1925 简单