您的位置:首页 > Web前端

【leetcode】Perfect Squares (#279)

2016-12-17 11:56 441 查看
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.

解析:

利用动态规划解决此问题:对于要求的当前节点而言都是从前面的节点转移过来的,只是这些转移节点并非一个,而是多个,比如1*1,2*2,3*3,,,那么相应的res[i-1]、res[i-4]、res[i-9]等等都是转移点。从这些候选项中找到最小的那个,然后加1即可。

算法实现代码:

//#include "stdafx.h"
#include <iostream>
#include <cstdio>
#include <climits>
#include <ctime>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <cstdlib>
#include <windows.h>
#include <string>
#include <cstring>
#include <cmath>

using namespace std;

class Solution {
public:
int numSquares(int n) {
vector<int> res(n + 1);
for (int i = 0; i <= n; ++i){
res[i] = i;
for (int j = 1; j * j <= i; ++j){
res[i] = min(res[i - j * j] + 1, res[i]);
}
}
return res
;
}
};

int main(){
Solution s;
cout<<s.numSquares(13);
return 0;
}


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