Sunday, April 9, 2017
279. Perfect Squares
二刷
因为i - x * x 永远比 i 小,所以 dp[i - x * x]一定是已经计算过的,不需要再检查是否计算过
dp[i] 可以初始化为i 而不是 Integer.MAX_VALUE 因为至少可以做到 1 + 1 + 1...
35.77 %
class Solution {
public int numSquares(int n) {
if (n <= 0) {
return 0;
}
// dp[i] -> min number of perfect square numbers sum up to i
int[] dp = new int[n + 1];
dp[0] = 0;
dp[1] = 1;
int x;
for (int i = 2; i <= n; i++) {
dp[i] = i;
x = 1;
while (i - x * x >= 0) {
dp[i] = Math.min(dp[i], dp[i - x * x] + 1);
x++;
}
}
return dp[n];
}
}
一刷
dp[n] indicates that the perfect squares count of the given n
26.50%
public class Solution {
public int numSquares(int n) {
if (n <= 0) return -1;
int[] count = new int[n + 1];
count[0] = 0;
for (int i = 1; i <= n; i++) {
count[i] = i;
for (int j = 1; j * j <= i; j++) {
count[i] = Math.min(count[i], count[i - j * j] + 1);
}
//System.out.println(count[i]);
}
return count[n];
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment