版权声明:版权归个人所有,未经博主允许,禁止转载 https://blog.csdn.net/danspace1/article/details/87820924
原题
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, …) which sum to n.
Example 1:
Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.
Example 2:
Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.
解法
动态规划, 用dp[i]表示数字组成数字i的最少完美平方的个数, 状态转移方程
dp[i] = min(dp[i], dp[i - j*j]
为方便迭代, 初始化dp[0] = 0, dp[1] = 1, dp[i] = n, 遍历2到n, 不断更新dp[i].
以n = 13为例, 13 - 2*2 = 9, 那么dp[13] = min(dp[13] + dp[9] + 1), 我们求dp[9]的最少完美平方的个数, 加上1就是dp[13]的结果.
Time: O(n)
Space: O(n)
代码
class Solution:
def numSquares(self, n: 'int') -> 'int':
dp = [n]*(n+1)
dp[0] = 0
dp[1] = 1
for i in range(2, n+1):
j = 1
while j*j <= i:
dp[i] = min(dp[i], dp[i-j*j] + 1)
j += 1
return dp[-1]