三角形(Triangle)动态规划 详细思路

题目:Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.

输入输出:

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

The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).

解决思路:

class Solution {
    public int minimumTotal(List> triangle) {
    
        //用一个数组存下层n行最小的和
        int[] result = new int[triangle.size()+1];
        
        //从最后一行开始,不断更新result数组
        for(int i = triangle.size() - 1;i >=0;i--){
            
            //每次加上一行数组,更新result数组
            for(int j = 0;j <= i;j++){
            int left = triangle.get(i).get(j) + result[j];
            int right = triangle.get(i).get(j) + result[j+1];
            result[j] =   left > right ? right : left;
            }
        }
        
        //最后返回最小值
        return result[0];
    }
}

思路:动态规划,倒着计算,每次根据前面的结果,得到后面的结果。 

 

你可能感兴趣的:(动态规划,leetcode,算法)