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
, return3
because12 = 4 + 4 + 4
; given n =13
, return2
because13 = 4 + 9
.题目大意:给定一个正整数n,找出最少的完全平方数使他们的和等于n。
思路:dp,dp[i]表示第i个数至少有多少个完全平方数的和组成。
dp[0] = 0 dp[1] = dp[0]+1 = 1 dp[2] = dp[1]+1 = 2 dp[3] = dp[2]+1 = 3 dp[4] = Min{ dp[4-1*1]+1, dp[4-2*2]+1 } = Min{ dp[3]+1, dp[0]+1 } = 1 dp[5] = Min{ dp[5-1*1]+1, dp[5-2*2]+1 } = Min{ dp[4]+1, dp[1]+1 } = 2 . . . dp[13] = Min{ dp[13-1*1]+1, dp[13-2*2]+1, dp[13-3*3]+1 } = Min{ dp[12]+1, dp[9]+1, dp[4]+1 } = 2 . . . dp[n] = Min{ dp[n - i*i] + 1 }, n - i*i >=0 && i >= 1
代码:
package DP; import java.util.Arrays; /** * @Author OovEver * @Date 2017/12/17 17:25 */ public class LeetCode279 { 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(dp[i - j * j] + 1, min); j++; } dp[i] = min; } return dp[n]; } }