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
.
Analyse: dp[m] = min{ dp[m - i * i] + 1 } as long as i * i <= m.
Runtime: 400ms.
1 class Solution { 2 public: 3 int numSquares(int n) { 4 if(n <= 1) return n; 5 6 vector<int> dp(n + 1, INT_MAX); 7 dp[0] = 0; 8 dp[1] = 1; 9 10 for(int i = 1; i <= n; i++){ 11 for(int j = 1; j * j <= i; j++) 12 dp[i] = min(dp[i], dp[i - j * j] + 1); 13 } 14 return dp[n]; 15 } 16 };
原文:http://www.cnblogs.com/amazingzoe/p/4796671.html