您的位置:首页 > Web前端

leetcode@ [279]Perfect Squares

2015-11-02 14:11 351 查看
https://leetcode.com/problems/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
.

class Solution {
public:
int getMaximumSquare(int n){
int ret = (int)sqrt(n);
return ret;
}
int dfs(int load, vector<int> &dp){
if(dp[load]) return dp[load];
if(load == 0){
return 0;
}

int next = getMaximumSquare(load);
int Min = numeric_limits<int>::max();
for(int v=next;v>=1;v--){
if(load-v*v >= 0){
Min = min(Min, dfs(load-v*v, dp));
}
}
dp[load] = Min + 1;
return dp[load];
}
int numSquares(int n) {
vector<int> dp(n+1);
for(int i=0;i<dp.size();++i) dp[i] = 0;

dp
= dfs(n, dp);
return dp
;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: