leetcode 279. Perfect Squares

传送门

 

279. Perfect Squares

    My Submissions
QuestionEditorial Solution
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值