LeetCode解题报告 279. Perfect Squares [medium]
2016-12-17 00:52
507 查看
题目描述
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.
解题思路
题目很容易理解,将一个数分解为几个平方数的和,返回最小需要的平方数的个数。用动态规划求解,一个数x如果可以表示成a+b*b,那么最后所求的结果就是组成a所需要的平方数的个数再加1。
状态转移方程为dp[a+b*b]=min(dp[a]+1, dp[a+b*b])。
将一个长度为x的数组,完全平方数初始化为1,其余数初始化为无穷大,如果一个数是完全平方数,那么返回的值就是它本身,也就是1;如果一个数不是完全平方数,那么返回的值就是dp[a]+1,因为此时dp[a+b*b]是无穷大。
代码如下:
class Solution { public: int numSquares(int n) { int dp[n+1]; for (int i=0; i<n+1; i++) { dp[i]=INT_MAX; } for (int i=0; i*i<=n; i++) { dp[i*i]=1; } for (int i=0; i<=n; i++) { for (int j=0; i+j*j<=n; j++) { dp[i+j*j]=min(dp[i]+1,dp[i+j*j]); } } return dp ; } };
时间复杂度
O(N)*O(sqrt(N))
相关文章推荐
- 【LeetCode】648.Replace Words(Medium)解题报告
- 【LeetCode】117.Populating Next Right Pointers in Each Node II(Medium)解题报告
- 【LeetCode】334.Increasing Triplet Subsequence(Medium)解题报告
- 【LeetCode】406.Queue Reconstruction by Height(Medium)解题报告
- LeetCode解题报告 452. Minimum Number of Arrows to Burst Balloons [medium]
- 【LeetCode】244.Shortest Word Distance II(Medium)解题报告
- 【LeetCode】435.Non-overlapping Intervals(Medium)解题报告
- 【LeetCode】228.Summary Ranges(Medium)解题报告
- LeetCode解题报告 413. Arithmetic Slices [medium]
- 【LeetCode】560.Subarray Sum Equals K(Medium)解题报告
- 【LeetCode】40.Combination Sum II(Medium)解题报告
- LeetCode解题报告 122. Best Time to Buy and Sell Stock II [medium]
- 【LeetCode】77.Combinations(Medium)解题报告
- 【LeetCode】47.Permutations II(Medium)解题报告
- 【LeetCode】289.Game of Life(Medium)解题报告
- 【LeetCode】98. Validate Binary Search Tree(Medium)解题报告
- 【LeetCode】11.Container With Most Water(Medium)解题报告
- LeetCode解题报告 392. Is Subsequence [medium]
- LeetCode解题报告 309. Best Time to Buy and Sell Stock with Cooldown[medium]
- LeetCode解题报告 394. Decode String [medium]