[LeetCode]Perfect Squares
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.
For example, given n = 12
, return 3
because 12 = 4 + 4 + 4
; given n = 13
, return 2
because 13 = 4 + 9
.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
DP问题,计算1-n的每个值得perfect squares,从小到大计算。
递推公式f[i]=min(f[i],f[i-j*j]+1)。
1 class Solution { 2 public: 3 int numSquares(int n) { 4 vector<int> f(n+1,0); 5 f[1]=1; 6 for(int i=2;i<=n;i++) 7 { 8 int local_min = INT_MAX; 9 int j=1; 10 while(j*j<=i) 11 { 12 if(j*j==i) 13 { 14 local_min = 1; 15 break; 16 } 17 else 18 { 19 local_min = min(local_min,f[i-j*j]+1); 20 j++; 21 } 22 } 23 f[i]=local_min; 24 } 25 return f[n]; 26 } 27 };