leetcode-120. 三角形最小路径和

题目:

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

例如,给定三角形:

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

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

答案:

class Solution {
    public int minimumTotal(List<List<Integer>> triangle) {
        for (int j = triangle.size(); j > 1 ; j--) {
            for (int i = 0; i < j-1 ; i++) {
                int rootValue = triangle.get(j - 2).get(i);
                int leftValue = triangle.get(j - 1).get(i);
                int rightValue = triangle.get(j - 1).get(i+1);
                int minValue = getMin(rootValue + leftValue, rootValue + rightValue);
                triangle.get(j-2).set(i, minValue);
            }
        }
        return triangle.get(0).get(0);
    }
    
    public int getMin(int left, int right) {
        return left <= right?left:right;
    }
}

猜你喜欢

转载自www.cnblogs.com/Grace-is-enough/p/9124246.html