[LeetCode] Perfect Squares
2015-11-06 18:34
369 查看
Given a positive integer n, find the least number of perfect square numbers (for example,
For example, given 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
Java:
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
解题思路
动态规划法。初始化时令dp[i * i] = 1,状态转移方程为
dp[i + j * j] = min(dp[i] + 1, dp[i + j * j]);
实现代码
C++:// Runtime: 544 ms class Solution { public: int numSquares(int n) { vector<int> dp(n + 1, 0x7fffffff); for (int i = 0; i * i <= n; i++) { dp[i * i] = 1; } for (int i = 1; i <= n; i++) { for (int j = 1; i + j * j <= n; j++) { dp[i + j * j] = min(dp[i] + 1, dp[i + j * j]); } } return dp ; } };
Java:
// Runtime: 69 ms public class Solution { public int numSquares(int n) { int dp[] = new int[n + 1]; Arrays.fill(dp, Integer.MAX_VALUE); for (int i = 1; i * i <= n; i++) { dp[i * i] = 1; } for (int i = 1; i <= n; i++) { for (int j = 1; i + j * j <= n; j++) { dp[i + j * j] = Math.min(dp[i] + 1, dp[i + j * j]); } } return dp ; } }
相关文章推荐
- 结合LayoutIt学习Bootstrap的探索
- Express使用html模板
- js获取前后的日期以及日期格式化
- jquery写拉动条
- XML与JSON解析
- .net如何序列换对象为Json字符串
- 用HTML5播放IPCamera视频
- JQuery判断数组中是否包含某个元素$.inArray("js", arr);
- jquery模拟checkbox效果,以及background-size在jquery中的使用。
- js 事件冒泡和事件捕获
- 原生Javascript 省市区下拉列表插件
- 原生Javascript 省市区下拉列表插件
- HTML中将背景颜色渐变
- Codeforces 547B Mike and Feet
- JSP基本语法--Page指令 <%@page 属性=”内容“%>
- jquery ajax form serialize() 转json 数据,post 后台
- jQuery选择器大全
- 关于jquery--index()方法的简单理解
- JS 有关时间处理
- AngularJS开发指南03:HTML编译器