# Java求数塔（最优路径）问题

 9 12 15 10 6 8 2 18 9 5 19 7 10 4 16

（自底向顶）解析：

 59 50 49 38 34 29 21 28 19 21 19 7 10 4 16

（自底向顶）代码：

package dynamicProgramming;

public class TowerOfNumbers {

public static void tpWalk(int[][] tower) {
int[][] dpTower = new int[tower.length][];

dpTower[tower.length - 1] = tower[tower.length-1];
for(int i = tower.length - 2;i >= 0;i--) {
dpTower[i] = tower[i].clone();
for(int j = 0;j<dpTower[i].length;j++) {
if(dpTower[i+1][j] > dpTower[i+1][j+1])
dpTower[i][j] += dpTower[i+1][j];
else {
dpTower[i][j] += dpTower[i+1][j+1];
}
}
}

System.out.println("最优路径长度：" + dpTower[0][0]);

System.out.println("最优路径：");
int j=0;//路径节点
for(int i = 0;i<dpTower.length-1;i++) {
if(j<dpTower[i].length-1 && dpTower[i][j] < dpTower[i][j+1])
j =j+1;
System.out.print(tower[i][j] + "->");
}
if(j<dpTower[dpTower.length-1].length-1 && dpTower[dpTower.length-1][j] < dpTower[dpTower.length-1][j+1])
j =j+1;
System.out.println(tower[dpTower.length-1][j]);

}

public static void main(String[] args) {
int[][] tower = {{9},{12,15},{10,6,8},{2,18,9,5},{19,7,10,4,16}};
for(int i = 0;i<tower.length;i++) {
for(int j = 0;j<tower[i].length-1;j++) {
System.out.print(tower[i][j] + " ");}

System.out.println(tower[i][tower[i].length-1]);
}
tpWalk(tower);
}

}

 9 21 24 31 30 23 33 49 39 28 54 55 59 43 44

https://blog.csdn.net/theonegis/article/details/45801201

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120