考虑在下面被显示的数字金字塔. 写一个程序来计算从最高点开始在底部任意处结束的路径经过数字的和的最大. 每一步可以走到左下方的点也可以到达右下方的点. 7 38 8 10 2 74 4 4 52 6 5 在上面的样例中,从 7 到 3 到 8 到 7 到 5 的路径产生了最大和:30
输入格式:
第一个行包含 R(1<= R<=1000) ,表示行的数目. 后面每行为这个数字金字塔特定行包含的整数. 所有的被供应的整数是非负的且不大于 100.
输出格式:
单独的一行包含那个可能得到的最大的和.
输入样例:
在这里给出一组输入。例如:
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
输出样例:
在这里给出相应的输出。例如:
30
1、DFS法
import java.util.Scanner;
public class Main {
public static int sum = 0;//最大路径和
public static int N = 0;//N为行数,定义全局变量是为了方便在两个函数中存在
public static int [][]arr = new int [1000][1000];//
public static void DFS(int x,int y,int curr) {//x和y表示当前点坐标,curr表示(1,1)到点(x,y)走过的路径的和
if( x == N ) {
if(curr > sum) {
sum = curr;//终止条件:到达终点,结束递归,得到最大路径和
}
}
else {
DFS(x + 1,y,curr + arr[x + 1][y]);//左下方向走
DFS(x + 1,y + 1,curr + arr[x + 1][y + 1]);//右下方向走
}
}
public static void main(String []args) {
Scanner in = new Scanner(System.in);
N = in.nextInt();
for(int i = 1;i <= N;i++) {
for(int j = 1;j <= i;j++) {
arr[i][j] = in.nextInt();
}
}
DFS(1,1,arr[1][1]);
System.out.println(sum);
}
}
时间复杂度:o(2^n-1),运行超时
2.动态规划法(顺推法)
import java.util.Scanner;
public class Main {
public static int sum = 0;
public static int N = 0;
public static int [][]f = new int [1000][1000];
public static int max(int a,int b) {
return a>b ? a : b;
}
public static void main(String []args) {
Scanner in = new Scanner(System.in);
N = in.nextInt();
int [][]arr = new int[1000][1000];
for(int i = 1;i <= N;i++) {
for(int j = 1;j <= i;j++) {
arr[i][j] = in.nextInt();
}
}
f[1][1] = arr[1][1];
for (int x = 2;x <= N;x++) {
for (int y = 1;y <= x;y++ ) {
f[x][y] = max(f[x-1][y-1],f[x-1][y]) + arr[x][y];
}
}
for(int k = 1;k <= N;k++) {
sum = max(sum,f[N][k]);
}
System.out.println(sum);
}
}
3.动态规划法(逆推法)
import java.util.Scanner;
public class Main {
public static int sum = 0;
public static int N = 0;
public static int [][]f = new int [1000][1000];
public static int max(int a,int b) {
return a>b ? a : b;
}
public static void main(String []args) {
Scanner in = new Scanner(System.in);
N = in.nextInt();
int [][]arr = new int[1000][1000];
for(int i = 1;i <= N;i++) {
for(int j = 1;j <= i;j++) {
arr[i][j] = in.nextInt();
}
}
for(int k = 1;k <= N;k++){
f[N][k] = arr[N][k];
}
for (int x = N - 1;x > 0;x--) {
for (int y = 1;y <= x;y++ ) {
f[x][y] = max(f[x+1][y],f[x+1][y+1]) + arr[x][y];
}
}
System.out.println(f[1][1]);
}
}