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) 。 示例…
2
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数学·结合·enumeration
答案摘要
我们在 $[1, n)$ 的范围内枚举 和 ,然后计算 $c = \sqrt{a^2 + b^2}$,如果 是整数且 $c \leq n$,那么就找到了一个平方和三元组,答案加一。 枚举结束后,返回答案即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·结合·enumeration 题型思路
题目描述
一个 平方和三元组 (a,b,c) 指的是满足 a2 + b2 = c2 的 整数 三元组 a,b 和 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
解题思路
方法一:枚举
我们在 的范围内枚举 和 ,然后计算 ,如果 是整数且 ,那么就找到了一个平方和三元组,答案加一。
枚举结束后,返回答案即可。
时间复杂度 ,其中 是给定的整数。空间复杂度 。
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.