2024/9/25 Hot100 dp
This commit is contained in:
parent
153bda20f5
commit
9593c2606b
|
@ -2,6 +2,8 @@ package com.cool.hot100.dp;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Created with IntelliJ IDEA.
|
* Created with IntelliJ IDEA.
|
||||||
*
|
*
|
||||||
|
@ -13,8 +15,52 @@ import org.junit.Test;
|
||||||
*/
|
*/
|
||||||
public class Num279 {
|
public class Num279 {
|
||||||
|
|
||||||
|
private static final int[][] memory = new int[101][10001];
|
||||||
|
//
|
||||||
|
// static {
|
||||||
|
// for (int[] row : memory) {
|
||||||
|
// Arrays.fill(row, -1); // -1 表示没有计算过
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
static {
|
||||||
|
for (int[] row : memory) {
|
||||||
|
Arrays.fill(row, Integer.MAX_VALUE); // -1 表示没有计算过
|
||||||
|
}
|
||||||
|
memory[0][0] = 0;
|
||||||
|
}
|
||||||
|
|
||||||
public int numSquares(int n) {
|
public int numSquares(int n) {
|
||||||
|
for (int i = 1; i * i <= n; i++) {
|
||||||
|
for (int j = 0; j <= n; j++) {
|
||||||
|
if (j < i * i) {
|
||||||
|
memory[i][j] = memory[i - 1][j];
|
||||||
|
} else {
|
||||||
|
memory[i][j] = Math.min(memory[i - 1][j], memory[i][j - i * i] + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return memory[(int) Math.sqrt(n)][n];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public int numSquares1(int n) {
|
||||||
|
return dfs((int) Math.sqrt(n), n);
|
||||||
|
}
|
||||||
|
|
||||||
|
// i是指j比哪些i的平方大,j为当前数字
|
||||||
|
private int dfs(int i, int j) {
|
||||||
|
if (i == 0) {
|
||||||
|
return j == 0 ? 0 : Integer.MAX_VALUE;
|
||||||
|
}
|
||||||
|
if (memory[i][j] != -1) {
|
||||||
|
return memory[i][j];
|
||||||
|
}
|
||||||
|
if (i * i > j) {
|
||||||
|
return memory[i][j] = dfs(i - 1, j);
|
||||||
|
}
|
||||||
|
return memory[i][j] = Math.min(dfs(i - 1, j), dfs(i, j - i * i) + 1);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue