[279]Perfect Squares
2015-11-07 12:40
411 查看
【题目描述】
Given a positive integer n, find the least number of perfect square numbers (for example,
For example, given n =
【思路】
1.用动态规划。f[i]=min(f[i],f[i-j*j])
2.根据四平方和定理和https://leetcode.com/discuss/56982/o-sqrt-n-in-ruby-and-c,
... a square if and only if each prime factor occurs to an even power in the number's prime factorization.
... a sum of two squares if
and only if each prime factor that's 3 modulo 4 occurs to an even power in the number's prime factorization.
... a sum of three squares if
and only if it's not of the form 4a(8b+7) with integers a and b.
... a sum of four squares.
Period. No condition. You never need more than four。
【代码】
<span style="font-size:14px;">class Solution {
public:
int numSquares(int n) {
vector<int> f(n+1,INT_MAX);
for(int i=1;i*i<=n;i++){
f[i*i]=1;
}
for(int i=2;i<=n;i++){
if(f[i]==1) continue;
for(int j=1;j*j<i;j++){
f[i]=min(f[i],f[i-j*j]+1);
}
}
return f
;
}
};</span>
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
3because
12 = 4 + 4 + 4; given n =
13, return
2because
13 = 4 + 9.
【思路】
1.用动态规划。f[i]=min(f[i],f[i-j*j])
2.根据四平方和定理和https://leetcode.com/discuss/56982/o-sqrt-n-in-ruby-and-c,
... a square if and only if each prime factor occurs to an even power in the number's prime factorization.
... a sum of two squares if
and only if each prime factor that's 3 modulo 4 occurs to an even power in the number's prime factorization.
... a sum of three squares if
and only if it's not of the form 4a(8b+7) with integers a and b.
... a sum of four squares.
Period. No condition. You never need more than four。
【代码】
<span style="font-size:14px;">class Solution {
public:
int numSquares(int n) {
vector<int> f(n+1,INT_MAX);
for(int i=1;i*i<=n;i++){
f[i*i]=1;
}
for(int i=2;i<=n;i++){
if(f[i]==1) continue;
for(int j=1;j*j<i;j++){
f[i]=min(f[i],f[i-j*j]+1);
}
}
return f
;
}
};</span>
class Solution { public: int numSquares(int n) { while(n%4==0) n/=4; if(n%8==7) return 4; for(int i=0;i*i<=n;i++){ int j=sqrt(n-i*i); if(i*i+j*j==n){ return !!i+!!j; } } return 3; } };
相关文章推荐
- HDU 4044 GeoDefense
- 在win7系统下如何修改文件后缀名?win7修改文件后缀名html方法
- 再探 Ext JS 6 (sencha touch/ext升级版) 变化篇 (编译命令、滚动条、控制层、模型层、路由)
- jquery UI Datepicker时间控件的使用方法(终结版)
- Java 中BufferedReader & InputStreamReader 用法
- 教程: Play Framework 2 with Scala, Anorm, JSON, CoffeeScript, jQuery & Heroku
- poj--3905--Perfect Election(2-sat)
- poj--3905--Perfect Election(2-sat)
- CSS3绘制不规则图形的一些方法示例
- jquery UI Datepicker时间控件的使用方法(加强版)
- CSS样式--实际开发总结
- CSS样式--实际开发总结
- js 替换反斜杠(\)
- [转]css样式加载顺序及覆盖顺序深入理解
- 7个你可能不认识的css单位
- jquery UI Datepicker时间控件的使用方法(基础版)
- JavaScript代码性能优化总结
- js面向对象初步学习
- 2015前端组件化框架之路
- React学习