Leetcode Perfect Squares
2016-06-18 02:26
417 查看
Given a positive integer n, find the least number of perfect square numbers (for example,
For example, given n =
Difficulty: Medium
Solution: DP
public class Solution {
public int numSquares(int n) {
int max = (int) Math.sqrt(n);
int[] dp = new int[n+1];
Arrays.fill(dp, Integer.MAX_VALUE);
for(int i=1; i<=n; i++){
for(int j=1; j<=max; j++){
if(i==j*j){
dp[i]=1;
}else if(i>j*j){
dp[i]=Math.min(dp[i], dp[i-j*j] + 1);
}
}
}
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.
Difficulty: Medium
Solution: DP
public class Solution {
public int numSquares(int n) {
int max = (int) Math.sqrt(n);
int[] dp = new int[n+1];
Arrays.fill(dp, Integer.MAX_VALUE);
for(int i=1; i<=n; i++){
for(int j=1; j<=max; j++){
if(i==j*j){
dp[i]=1;
}else if(i>j*j){
dp[i]=Math.min(dp[i], dp[i-j*j] + 1);
}
}
}
return dp
;
}
}
相关文章推荐
- 对于json格式数据节点的解析
- 抛砖引玉:如何在 React 中使用 semantic-ui 的 fixed menu 和 sidebar
- JS 基于面向对象的 轮播图1
- JS 基于面向对象的 轮播图2
- html定位城市
- jQuery监听输入框的值变化
- 又被事件冒泡坑了一把,这次要彻底弄懂浏览器的事件流
- angularJs的ng-class切换class
- HTML特殊字符的html、js、css写法汇总
- 用 CSS 隐藏页面元素的 5 种方法
- 使用 <pre> 标签样式的注意事项
- 火狐 bootstrap pre 不换行
- nvm管理node命令
- div加链接 html给div加超链接实现点击div跳转的方法
- 移动前端头部标签(HTML5 head meta)
- 请问怎么判断子栏目的第一个,并为它加上样式
- js 优秀资源
- 单页面右侧导航样式
- React: ES5 和 ES6 比较
- web前端框架