題目:
給定正整數 n,找到若干個完全平方數(比如 1, 4, 9, 16, ...
)使得它們的和等於 n。你需要讓組成和的完全平方數的個數最少。
示例 1:
輸入: n =12
輸出: 3 解釋:12 = 4 + 4 + 4.
示例 2:
輸入: n =13
輸出: 2 解釋:13 = 4 + 9.
解題思路:
使用動態規划的作法,前確定之前的整數n由幾個完全平方數構成。
class Solution { public int numSquares(int n) { int[] a =new int [n+1]; a[0] = 0; a[1] = 1; for(int i = 2; i <= n;i++) { int temp = Integer.MAX_VALUE; //int temp1 = Integer.MIN_VALUE; for(int j = 1; j*j <= i;j++) { temp = Math.min(temp,a[i-j*j]); } a[i] = temp + 1; } return a[n]; } }