279. Perfect Squares
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
.
本题可以使用DP来做,也可以使用BFS来做;
如果使用DP来做,则需要推算出状态方程,这里面的状态方程开始并没有想出来,看了答案后才做出来,代码如下:
1 public class Solution { 2 public int numSquares(int n) { 3 int[] dp = new int[n+1]; 4 Arrays.fill(dp,Integer.MAX_VALUE); 5 dp[0] = 0; 6 for(int i=1;i<=n;i++){ 7 for(int j=1;j*j<=i;j++){ 8 dp[i] = Math.min(dp[i],dp[i-j*j]+1); 9 } 10 } 11 return dp[n]; 12 } 13 }