279. Perfect Squares
来源:互联网 发布:网络销售授权 编辑:程序博客网 时间:2024/05/22 02:02
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
.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
The idea using DP is simple, For a number N, if some int i*i = N, then dp[N] = 1;
else for every k from 1 -> n - 1 dp[N] = min(dp[k] + dp[n-k]);
Code:
public class Solution { public int numSquares(int n) { int[] dp = new int[n + 1]; int i = 0; while(i*i <= n){ dp[i*i] = 1; i++; } for(i = 2; i < dp.length; i++){ if(dp[i] == 0){ int temp = Integer.MAX_VALUE; for(int k = 1; k < i; k++){ temp = Math.min(temp,dp[k] + dp[i - k]); } dp[i] = temp; } } return dp[n]; }}However, this gets TLE, since it actually requires O(N2) time.
How to optimize, for example 12 = 4 + 4 + 4, we get 12 = 1 + 11, 2 + 10 3 + 9....., which is unnecessary.
for 2 + 10 , it actually the same with 1 + 11, because they all will get factor 1,
So what we could do is to pick k that is the square of some int.
public class Solution { public int numSquares(int n) { int[] dp = new int[n + 1]; int i = 0; while(i*i <= n){ dp[i*i] = 1; i++; } for(i = 2; i < dp.length; i++){ if(dp[i] == 0){ int temp = Integer.MAX_VALUE; for(int k = 1; k * k < i; k++){ temp = Math.min(temp,1 + dp[i - k*k]); } dp[i] = temp; } } return dp[n]; }}
- 279.Perfect Squares
- [leetcode] 279. Perfect Squares
- 279. Perfect Squares
- 279. Perfect Squares LeetCode
- leetcode 279. Perfect Squares
- leetcode 279. Perfect Squares
- [LeetCode]279. Perfect Squares
- 279. Perfect Squares
- 279. Perfect Squares
- 279. Perfect Squares
- LeetCode-279.Perfect Squares
- LeetCode *** 279. Perfect Squares
- 279. Perfect Squares
- 279. Perfect Squares
- 279. Perfect Squares
- leetcode.279. Perfect Squares
- 279. Perfect Squares
- 279. Perfect Squares
- 数据在内存中的存储
- C指针基础(一)
- 2017-03-12
- 后台服务器相关开发学习的路径
- 改变Android studio logcat中的字体大小和颜色
- 279. Perfect Squares
- Proteus标题栏
- Java单链表的操作
- 面试感悟----一名3年工作经验的程序员应该具备的技能
- bzoj 3991: [SDOI2015]寻宝游戏 (set+LCA+dfs序+虚树)
- C# 输入法
- AJAX——核心XMLHttpRequest对象
- CCF201403(2)经典窗口问题
- 贝叶斯估计和极大似然估计到底有何区别