cqupt @ 2022-11-18 22:56:54
最后一个测试点MLE了,我觉得已经把空间优化得最好了,还是空间超了,请教一下还有哪一点写得不好,或者优化得不好吗?或者说是java的问题?
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static int[][] dp;
public static ArrayList<ArrayList<Integer>> array;
public static void main(String[] args) {
int n = 0;
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
array = new ArrayList<>(n);
dp = new int[n][];
for(int i = 0; i <n; ++i) {
dp[i] = new int[i + 1];
for(int j =0; j <= i; ++j)
dp[i][j] = -1;
}
for(int i = 0; i < n; ++i) {
array.add(new ArrayList<Integer>(i));
for(int j = 0; j <= i; ++j) {
array.get(i).add(sc.nextInt());
}
}
System.out.println(solution(n, 0, 0));
}
private static int solution(int n, int x, int y) {
if(x == n - 1) {
dp[x][y] = array.get(x).get(y) + 1;
return array.get(x).get(y);
}
else {
if(dp[x + 1][y] == -1)
dp[x + 1][y] =solution(n, x + 1, y);
if(dp[x + 1][y + 1] == -1)
dp[x + 1][y + 1] = solution(n, x + 1, y + 1);
return Math.max(dp[x + 1][y + 1], dp[x + 1][y]) + array.get(x).get(y);
}
}
}
by goodluck321 @ 2023-03-11 20:54:18
这题最后一个测试点很迷啊!
滚动数组可以过
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[][] map = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
map[i][j] = input.nextInt();
}
}
// dp[i][j] = max(dp[i-1][j-1], dp[i-1][j]) + map[i][j]
int[][] dp = new int[2][n];
// init
dp[0][0] = map[0][0];
for (int i = 1; i < n; i++) {
for (int j = 0; j <= i; j++) {
if (j == 0) {
dp[i % 2][j] = dp[(i - 1) % 2][j] + map[i][j];
} else {
dp[i % 2][j] = Math.max(dp[(i - 1) % 2][j - 1], dp[(i - 1) % 2][j]) + map[i][j];
}
}
}
int res = 0;
for (int j = 0; j < n; j++) {
if (dp[(n - 1) % 2][j] > res) {
res = dp[(n - 1) % 2][j];
}
}
System.out.println(res);
}