Question
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.
Code
public class Solution {
public int numSquares(int n) {
if (n < 1) return 0;
int[] dp = new int[n + 1];
for (int i = 1; i <= n; i++) {
int min = Integer.MAX_VALUE;
for (int j = 1; j * j <= i; j++) {
min = Math.min(min, dp[i - j * j] + 1);
}
dp[i] = min;
}
return dp[n];
}
}
Solution
动态规划。
dp[i]表示数字i可以拆分成的完美平方数的最小值。
对于每一个数字i (1 <= i <= n),尝试将数字i拆分成j ^ 2 + x,其中j为从1到(j^2 <= i)的枚举。由于j^2已经是一个完美平方数,所以i的完美平方数的拆分值应该为x的完美平方数的拆分值 + 1(这个1就是j^2)
网友评论