[leetcode-279]Perfect Squares(java)
2015-09-25 08:16
363 查看
问题描述:
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即可。
代码如下:280ms
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即可。
代码如下:280ms
[code]public class Solution { public int numSquares(int n) { int[] res = new int[n+1]; res[0] = 0; for(int i = 1;i<=n;i++){ int minNum = Integer.MAX_VALUE; for(int base = 1;i-base*base>=0;base++){ if(res[i-base*base]<minNum) minNum = res[i-base*base]; } res[i] = minNum+1; } return res ; } }
相关文章推荐
- 【JS】手机屏幕旋转判断
- Symantec BE2012 0xe000fec9 报错
- Scala深入浅出进阶经典 第46讲: ClassTag 、Manifest、ClassManifest、TypeTag代码实战及其在Spark中的应用源码解析
- JSP学习之异常处理实例分析
- JS+CSS实现仿支付宝菜单选中效果代码
- JS实现仿QQ效果的三级竖向菜单
- 2015/9/25 吐槽
- html5 视频播放 上传文件 控件
- angular之性能优化
- Ember.js 入门指南——指定与路由关联的模型
- Ember.js 入门指南——模板渲染
- 纯 CSS 实现水平下拉菜单
- chart.js 2.0dev 在不同屏幕下的分辨率问题
- XHTML5 ----- 表单验证(用户名、密码和email检测)
- html5常用新增标签
- 九、使用SharedPreferences进行数据存储
- XHTML5 ----- 拖拽事件 (拖拽一段文字和图片案例)
- 关于表单的提交方式(html5)
- html5_ajax
- [Effective Java 读书笔记] 第三章类和接口 第十八--十九条