leecode_279 Perfect Squares
2016-06-10 06:30
330 查看
Given a positive integer n, find the least number of perfect square numbers (for example,
For example, given n =
bfs内存爆了,还是用dp吧
class Solution {
public:
int numSquares(int n) {
const int len=n+1;
int res[len];
for (int i=0;i<len;i++)
res[i]=INT_MAX;
for (int i=1;i*i<=n;i++)
res[i*i]=1;
for (int i=1;i<=n;i++) {
for (int j=1;j*j<=i;j++){
if (i+j*j>n)
break;
if (i+j*j<=n ){
res[i+j*j]=min(res[i]+1,res[i+j*j]);
}
}
}
// for (int i=1;i<=n;i++)
// cout<<i<<"("<<res[i]<<")"<<" ";
// cout<<endl;
return res
;
}
};
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.
bfs内存爆了,还是用dp吧
class Solution {
public:
int numSquares(int n) {
const int len=n+1;
int res[len];
for (int i=0;i<len;i++)
res[i]=INT_MAX;
for (int i=1;i*i<=n;i++)
res[i*i]=1;
for (int i=1;i<=n;i++) {
for (int j=1;j*j<=i;j++){
if (i+j*j>n)
break;
if (i+j*j<=n ){
res[i+j*j]=min(res[i]+1,res[i+j*j]);
}
}
}
// for (int i=1;i<=n;i++)
// cout<<i<<"("<<res[i]<<")"<<" ";
// cout<<endl;
return res
;
}
};
相关文章推荐
- leecode_241 Different Ways to Add Parentheses
- [TypeScript] Using Typings and Loading From node_modules
- Angular 2 + Electron 开发web和桌面应用
- reactor 类库,基于事件编程
- [TypeScript] Using Lodash in TypeScript with Typings and SystemJS
- JSP翻译到servlet的理解
- JSP内置对象和作用域
- JavaAPI之FeatureDescriptor
- 《CSS权威指南》学习记录——浮动
- JSONModel几个属性
- JSONModel 使用特性
- scss使用后的简单入门总结
- JS自定义函数(递归、回调、匿名函数)
- 修改js confirm alert 提示框文字
- [LeetCode]problem 117. Populating Next Right Pointers in Each Node II
- 使用mustache.js 模板引擎输出html
- AngularJS 神奇的表单
- JS 中面向对象的5种写法
- jQuery的ajax访问后台的函数,有时正常,有时报连接错误的问题总结
- jsp中EL表达式不好使