leetcode 279. Perfect Squares

传送门

279. Perfect Squares

   My Submissions
Total Accepted: 33524 Total Submissions: 102649 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.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

Show Similar Problems
 
题解:
 
四平方和定理这种可遇不可求的做法就不说了,说说dp:
 
 
dp[i]代表组成i的最少平方数的个数。至于状态转移,我们可以这样想:组成这个数的最小值要么就是本身,要么就是前面某一个数+一个平方数(所以看作值加上1),类似0-1背包的思想。
 

Submission Details

600 / 600 test cases passed.
Status: 

Accepted

Runtime: 461 ms
 1 class Solution {
 2 public:
 3     int numSquares(int n) {
 4         vector<int> dp(n+1,INT_MAX);
 5         dp[0] = 0;  
 6         dp[1] = 1;  
 7         for(int i=2; i<=n; i++) {  
 8             for(int j = 1;j * j <= i ;j++){
 9                 dp[i] = min(dp[i], dp[i - j * j] + 1);  
10             }  
11         }  
12         return dp[n];  
13     }
14 };
原文地址:https://www.cnblogs.com/njczy2010/p/5466263.html