Leetcode 279 Perfect Squares
2017-03-13 03:01
316 查看
Given a positive integer n, find the least number of perfect square numbers (for example,
For example, given n =
这是一个 dynamic programming 的问题
初次接触
可以理解为一个规划的策略问题
参考动态规划
在这个问题里面,给定一个数n,可能包含的最大的平方数有限,但是却可以有不同的组合。
题目的要求就是寻找min也即是能大就不小
其实是需要递归遍历找出最小值的问题
在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.
这是一个 dynamic programming 的问题
初次接触
可以理解为一个规划的策略问题
参考动态规划
在这个问题里面,给定一个数n,可能包含的最大的平方数有限,但是却可以有不同的组合。
题目的要求就是寻找min也即是能大就不小
其实是需要递归遍历找出最小值的问题
在DP里面有一个很重要的思想就是存储中间值,这样就不需要进行重复的计算
public class Solution { public int numSquares(int n) { int[] dp = new int[n + 1]; Arrays.fill(dp, Integer.MAX_VALUE); dp[0] = 0; for(int i = 1; i <= n; ++i) { int min = Integer.MAX_VALUE; int j = 1; while(i - j*j >= 0) { min = Math.min(min, dp[i - j*j] + 1); ++j; } dp[i] = min; } return dp ; } }
相关文章推荐
- leetcode(279). Perfect Squares
- [leetcode] 279 Perfect Squares(DP,四平方和定理)
- [leetcode279] perfect squares
- Leetcode #279 Perfect Squares
- [leetcode 279]Perfect Squares
- (LeetCode 279) Perfect Squares
- LeetCode 279 Perfect Squares
- LeetCode(279)Perfect Squares
- LeetCode 279: Perfect Squares
- Perfect Squares - LeetCode 279
- 【leetcode】Perfect Squares (#279)
- LeetCode[279] Perfect Squares
- [LeetCode#279] Perfect Squares
- leetcode 279: Perfect Squares
- leetcode279:Perfect Squares
- leetcode279-Perfect Squares
- LeetCode 279 Perfect Squares 题解
- [Leetcode] #279 Perfect Squares (BFS, DP)
- LeetCode #279 - Perfect Squares - Medium
- leetcode:数学: Perfect Squares(279)