Perfect Squares
Total Accepted: 18854 Total Submissions: 63048 Difficulty: Medium
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
.
dp
f(n) = min{f(n-1),f(n-4),f(n-9)...f(n-k*k)}+1,其中k*k <=n && k>=1;
class Solution { public: int numSquares(int n) { vector<int> dp(n+1,0); for(int i=1;i<=n;i++){ int k = INT_MAX ,j=1; while(j*j <= i){ k = min(k,dp[i-j*j]+1); j++; } dp[i] = k; } return dp.back(); } };