1,二维从上到下规划
分析:
- 如果用dfs,下面就会存在重叠求上方某一位置最大值的情况
- 这种情况下并没有重新开辟空间,一不失为一种好方法
import java.util.Scanner;
public class Main {
public static int n;
public static int a[][];
public static void main(String[] args) {
Scanner sca = new Scanner(System.in);
n = sca.nextInt();
a = new int[n][];
for(int i = 0; i < n; i ++) {
a[i] = new int[i + 1];
for(int j = 0; j <= i; j ++) {
a[i][j] = sca.nextInt();
if(i == 0) {
a[i][j] = a[i][j];
}
else if(j == 0) {
a[i][j] += a[i - 1][j];
}
else if(j == i){
a[i][j] += a[i - 1][j - 1];
}
else {
a[i][j] = max(a[i][j] + a[i - 1][j - 1],a[i][j] + a[i - 1][j]);
}
}
}
int max = 0;
for(int i = 0; i < n; i ++) {
if(a[n - 1][i] > max) {
max = a[n - 1][i];
}
}
System.out.println(max);
}
private static int max(int i, int j) {
if(i > j) {
return i;
}
return j;
}
}
运行结果1:
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
30
2.滚动以为数组存放,并从下向上判断(优化)
分析:
- 从下往上就可以无需判断太多边界问题,也是一种优化
- 如果用dfs,下面就会存在重叠求下面某一位置最大值的情况
- 利用滚动dp数组,节省空间
import java.util.Scanner;
public class Main {
public static int n;
public static int a[][];
public static int dp[];
public static void main(String[] args) {
Scanner sca = new Scanner(System.in);
n = sca.nextInt();
a = new int[n][];
dp = new int[n];
for(int i = 0; i < n; i ++) {
a[i] = new int[i + 1];
for(int j = 0; j <= i; j ++) {
a[i][j] = sca.nextInt();
}
}
//初始化dp
for(int i = n - 1; i >= 0; i --) {
dp[i] = a[n - 1][i] ;
}
for(int i = n - 2; i >= 0; i --) {
for(int j = 0; j <= i ; j ++) {
dp[j] = max(dp[j] + a[i][j], dp[j + 1] + a[i][j]);
}
}
System.out.println(dp[0]);
}
private static int max(int i, int j) {
if(i > j) {
return i;
}
return j;
}
}
运行结果1:
5
3
9 2
4 5 6
3 5 3 2
3 4 6 9 4
29