leetcode 279. Perfect Squares
题目
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.
解法1:DP
递推公式为:
while j**2<=i:
dp[i] = min(dp[i],dp[i-j**2]+1)
代码
class Solution(object):
def numSquares(self, n):
"""
:type n: int
:rtype: int
"""
if n == 0:
return 0
dp = [float('inf')]*(n+1)
dp[0] = 0
dp[1] = 1
for i in range(2,n+1):
j = 1
while j**2<=i:
dp[i] = min(dp[i],dp[i-j**2]+1)
j+=1
return dp[n]
c++版本
class Solution {
public:
int numSquares(int n) <