码迷,mamicode.com
首页 > 其他好文 > 详细

120. 三角形最小路径和

时间:2020-04-12 20:21:28      阅读:63      评论:0      收藏:0      [点我收藏+]

标签:tco   wrk   nim   list   return   nbsp   min   problems   ref   

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

例如,给定三角形:

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

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

class Solution {
    public int minimumTotal(List<List<Integer>> trian) {
        int n = trian.get(trian.size() - 1).size();
        int[][] dp = new int[n + 1][n + 1];
        for(int i = n - 1;i >= 0;i--){
            List<Integer> list = trian.get(i);
            for(int j = 0;j < list.size();j++){
                dp[i][j] = Math.min(dp[i + 1][j],dp[i + 1][j + 1]) + list.get(j);
            }
        }
        return dp[0][0];
    }
}

 

120. 三角形最小路径和

标签:tco   wrk   nim   list   return   nbsp   min   problems   ref   

原文地址:https://www.cnblogs.com/zzytxl/p/12687241.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!