代码:
package LQB19;
import java.util.Scanner;
/*
* 数字三角形
*/
public class T2 {
public static void main(String[] args) {
// int[][] matrix = {{ 7}, { 3, 8}, { 8, 1, 0}, { 2, 7, 4, 4}, { 4, 5, 2, 6, 5}};
Scanner sc = new Scanner(System.in);
while ( sc.hasNext() ) {
int line = sc.nextInt();
int[][] matrix = new int[line][line];
for (int i = 0; i < line; i++) {
for (int j = 0; j < i + 1; j++) {
matrix[i][j] = sc.nextInt();
}
}
System.out.println(maxSum2(matrix));
}
}
// 动态规划
public static int maxSum2(int[][] matrix) {
int len = matrix.length - 1;
int[] max = matrix[len];//最后一层的元素
for (int i = len-1; i >= 0; i--) {//从倒数第二行开始循环,因为最后一行我们已经初始化过了
for (int j = 0; j <= i; j++) {
//动态数组的值就是当前行的元素相邻的最大值+上一层多对应的元素。
max[j] = Math.max(max[j], max[j + 1]) + matrix[i][j];
}
}
return max[0];
}
}