数字三角形问题(动态规划)

题目描述:

在上面的数字三角形中寻找一条从顶部到底边的路径,使得路径上所经过的数字之和最大。路径上的每一步都只能往左下或 右下走。只需要求出这个最大和即可,不必给出具体路径。 三角形的行数大于1小于等于100,数字为 0 - 99。

输入描述:输入共有N+1行,第1行为三角形的高度N,第二行到N+1行为每个点的值

输出描述:输出最大值。

示例输入:

5
8
3 8
8 1 0
4 7 5 4
3 5 2 6 5

输出:31

代码实现

import java.util.Scanner;

public class JinBi {

    public static void main(String[] args) {
        // 输入高度N
        Scanner in = new Scanner(System.in);
        int N = in.nextInt();
        int[][] nums = new int[N][N];
        for (int i = 0; i < N; i++) {
            for (int j = 0; j <= i; j++)
                nums[i][j] = in.nextInt();
        }
        if (N == 1) {
            System.out.println(nums[0][0]);
        } else {
            // 从倒数第二行开始
            for (int k = N - 2; k >= 0; k--) {
                for (int m = 0; m <= k; m++) {
                    nums[k][m] += Math.max(nums[k + 1][m], nums[k + 1][m + 1]);
                }
            }
        }
        System.out.println(nums[0][0]);

    }

}

参考博客:

https://blog.csdn.net/linghuainian/article/details/86001906

https://blog.csdn.net/baidu_28312631/article/details/47418773

https://blog.csdn.net/weixin_30414155/article/details/95053327

原文地址:https://www.cnblogs.com/HuangYJ/p/12805286.html