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
.
思路
这是一道非常典型的动态规划题目。
当前如果为元素n,需要找到这个元素n的平方根,然后依次减去平方根的数目,找到前1,4,9,16个元素的Perfect Squares数目。构成一个DP。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public class Solution { public int numSquares(int n) { List<Integer> dp = new ArrayList<Integer>(); dp.add(0); dp.add(1); for(int i = 2; i <= n; i++){ int max_root = (int) Math.floor(Math.sqrt((double) i)); int min_square = Integer.MAX_VALUE; for(int j = 1; j <= max_root; j++){ int tmp = dp.get(i - j * j) + 1; if(tmp < min_square) min_square = tmp; } dp.add(min_square); } return dp.get(dp.size()-1); } }
|