题目一:数塔问题
给定一个数塔,其存储形式为如下所示的下三角矩阵。在此数塔中,从顶部出发, 在每一节点可以选择向下走还是向右走,一直走到底层。请找出一条路径,使路径上 的数值和最大。
输入样例(数塔):
9
15
10 6 8
2 18 9 5
19 7 10 4 16
输出样例(最大路径和):
59
package suanfa_test3;
public class shu_ta {
static int[][] tower1 = { { 9 }, { 12, 15 }, { 10, 6, 8 }, { 2, 18, 9, 5 },
{ 19, 7, 10, 4, 16 } }; // 5行5列;tower1原始数塔
static int[][] tower2 = { { 9 }, { 12, 15 }, { 10, 6, 8 }, { 2, 18, 9, 5 },
{ 19, 7, 10, 4, 16 } }; // tower2求解数组
static int[][] tower3 = new int[5][5]; // 求解路径,0代表向下走,1代表向右下走
public static void main(String[] args) { // 第4层至第1层,求解最大值及路径
for (int i = 3; i >= 0; i--) {
for (int j = 0; j <= i; j++) {
if (tower2[i + 1][j] > tower2[i + 1][j + 1]) {
tower2[i][j] += tower2[i + 1][j];
tower3[i][j] = 0;
} else {
tower2[i][j] += tower2[i + 1][j + 1];
tower3[i][j] = 1;
}
}
}
System.out.println("最大值是:" + tower2[0][0]);
// 输出路径
int j = 0;// 列下标
for (int i = 0; i <= 3; i++) {
System.out.print(tower1[i][j] + " ");
j += tower3[i][j];
}
System.out.println(tower1[4][j]);
}
}