279. Perfect Squares
2016-07-17 17:28
183 查看
Given a positive integer n, find the least number of perfect square numbers (for example,
n.
For example, given n =
n =
Credits:
Special thanks to
@jianchao.li.fighter for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
优化后的做法,代码:
class Solution {
public:
int numSquares(int n) {
vector<int> dp(n+1,INT_MAX);
for(int i=0,j=0;j<=n;j=i*i){
dp[j]=1;
++i;
}
for(int i=2;i<=n;++i){
if(dp[i]!=1){
for(int j=1,k=1;k<i;k=j*j){
dp[i]=min(dp[i],1+dp[i-k]);
j++;
}
}
}
return dp
;
}
};
1, 4, 9, 16, ...) which sum to
n.
For example, given n =
12, return
3because
12 = 4 + 4 + 4; given
n =
13, return
2because
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
class Solution { public: int numSquares(int n) { vector<int> dp(n+1,INT_MAX); vector<int> num; if(n<4) return n; dp[1]=1; int m=1; for(int i=1;m<=n;) { if(m<0) break; dp[m]=1; num.push_back(m); i++; m=i*i; } for(int i=1;i<=n;++i) { for(int j=0;j<num.size();++j) if(dp[i]!=INT_MAX&&(i+num[j]<=n)) dp[i+num[j]]=min(dp[num[j]+i],1+dp[i]); } // cout<<dp ; return dp ==INT_MAX?n:dp ; } };
优化后的做法,代码:
class Solution {
public:
int numSquares(int n) {
vector<int> dp(n+1,INT_MAX);
for(int i=0,j=0;j<=n;j=i*i){
dp[j]=1;
++i;
}
for(int i=2;i<=n;++i){
if(dp[i]!=1){
for(int j=1,k=1;k<i;k=j*j){
dp[i]=min(dp[i],1+dp[i-k]);
j++;
}
}
}
return dp
;
}
};
相关文章推荐
- Javascript面向对象编程(三):非构造函数的继承
- Javascript面向对象编程(二):构造函数的继承
- Javascript 面向对象编程(一):封装
- Word 2013自定义样式
- HTML5-3
- Js中诡异的Array.length
- CSS3过渡transition
- caffe 进行自己的imageNet训练分类:loss一直是87.3365,accuracy一直是0
- jsp-servlet监听器
- javascript变量
- HTML5-2
- [Usaco2008 Feb]hotel旅馆(线段树)
- HtmlHelper拓展实现CheckBoxList
- CSS box-reflect倒影效果
- bootstrap完整导航栏
- js学习笔记:命名空间
- css布局之"display"属性
- JS学习笔记:变量提升
- JavaScript:正则表达式初体验
- Codeforces Round #305 (Div. 1) B. Mike and Feet(并查集)