LeetCode 题解工作台
完全平方数
给你一个整数 n ,返回 和为 n 的完全平方数的最少数量 。 完全平方数 是一个整数,其值等于另一个整数的平方;换句话说,其值等于一个整数自乘的积。例如, 1 、 4 、 9 和 16 都是完全平方数,而 3 和 11 不是。 示例 1: 输入: n = 12 输出: 3 解释: 12 = 4 +…
3
题型
6
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们定义 表示使用数字 $1, 2, \cdots, i$ 的完全平方数组成和为 的最少数量。初始时 $f[0][0] = 0$,其余位置的值均为正无穷。 我们可以枚举使用的最后一个数字的数量 ,那么:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个整数 n ,返回 和为 n 的完全平方数的最少数量 。
完全平方数 是一个整数,其值等于另一个整数的平方;换句话说,其值等于一个整数自乘的积。例如,1、4、9 和 16 都是完全平方数,而 3 和 11 不是。
示例 1:
输入:n =12输出:3 解释:12 = 4 + 4 + 4
示例 2:
输入:n =13输出:2 解释:13 = 4 + 9
提示:
1 <= n <= 104
解题思路
方法一:动态规划(完全背包)
我们定义 表示使用数字 的完全平方数组成和为 的最少数量。初始时 ,其余位置的值均为正无穷。
我们可以枚举使用的最后一个数字的数量 ,那么:
其中 表示最后一个数字 的完全平方数。
不妨令 ,那么有:
将二式代入一式,我们可以得到以下状态转移方程:
最后答案即为 。
时间复杂度 ,空间复杂度 。其中 为 的整数部分。
注意到 只与 和 有关,因此我们可以将二维数组优化为一维数组,空间复杂度降为 。
相似题目:
class Solution:
def numSquares(self, n: int) -> int:
m = int(sqrt(n))
f = [[inf] * (n + 1) for _ in range(m + 1)]
f[0][0] = 0
for i in range(1, m + 1):
for j in range(n + 1):
f[i][j] = f[i - 1][j]
if j >= i * i:
f[i][j] = min(f[i][j], f[i][j - i * i] + 1)
return f[m][n]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Can the candidate identify the optimal approach between dynamic programming and BFS for solving the problem?
- question_mark
Does the candidate handle state transitions efficiently in dynamic programming or BFS?
- question_mark
How well does the candidate explain the trade-offs between time complexity and space complexity in different approaches?
常见陷阱
外企场景- error
Not considering the correct base case in dynamic programming, such as dp[0] = 0.
- error
For BFS, not properly managing the queue, leading to unnecessary computations or missing the shortest path.
- error
Assuming that a greedy approach will always yield the optimal solution, which is not guaranteed.
进阶变体
外企场景- arrow_right_alt
What if the problem allows negative integers? This would add complexity in handling transitions.
- arrow_right_alt
How can this problem be solved with memoization instead of an iterative approach?
- arrow_right_alt
What happens if we only use odd perfect squares or squares of primes? This introduces constraints and alters the solution.