Leetcode 120 Triangle java实现

题目:

给定一个三践行,找出自顶向下的最小路径和。每一步只能移动到下一行中相邻的结点上。

例如:给定三角形:

[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]

自顶向下的最小路径和为11(2 + 3 + 5 + 1 = 11)

solution:

public int minimumTotal_1(List<List<Integer>> triangle) {

    int[][] dp = new int[triangle.size()][triangle.size()];

    dp[0][0] = triangle.get(0).get(0);

    int pSum = triangle.get(0).get(0), qSum = triangle.get(0).get(0);
    for (int i = 1; i < triangle.size(); ++i) {
        pSum += triangle.get(i).get(0);
        dp[i][0] = pSum;

        qSum += triangle.get(i).get(triangle.get(i).size() - 1);
        dp[i][triangle.get(i).size() - 1] = qSum;
    }

    for (int i = 1; i < triangle.size(); ++i) {
        for (int j = 1; j < triangle.get(i).size() - 1; ++j) {
            dp[i][j] = triangle.get(i).get(j) + Math.min(dp[i - 1][j - 1], dp[i - 1][j]);
        }
    }

    int minPath = dp[dp.length - 1][0];
    for (int j = 1; j < dp[dp.length - 1].length; ++j) {
        minPath = Math.min(dp[dp.length - 1][j], minPath);
    }

    return minPath;
}

参考博文:

https://www.jianshu.com/p/0e45ef4c604b

发布了640 篇原创文章 · 获赞 12 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/xiamaocheng/article/details/105068436
今日推荐