120. 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.

For example, given the following triangle

[
     [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).

一刷
题解:
dynamic programming, 这题不能用自顶向下只能用从下到上,因为为了更新dp[i]但不能利用到已被影响到的dp[i-1]的值。

120. Triangle_第1张图片
public class Solution {
    public int minimumTotal(List> triangle) {
        if(triangle == null || triangle.size() == 0)
            return 0;
        int rowNum = triangle.size();
        List lastRow = triangle.get(rowNum - 1);
        int[] paths = new int[rowNum];
        
        for(int i=0; i=0; i--){
            for(int j = 0; j < triangle.get(i).size(); j++){
                paths[j] = triangle.get(i).get(j) + Math.min(paths[j], paths[j+1]);
            }
        }
        
        return paths[0];
    }
}

二刷
dp

public class Solution {
    public int minimumTotal(List> triangle) {
        int deep = triangle.size();
        if(deep == 1) return triangle.get(0).get(0);
        int[] dp = new int[triangle.get(deep-1).size()];
        for(int i=0; i=0; layer--){
            for(int i=0; i<=layer; i++){
                //find the lesser ot its two children, and sum the current value in the triangle with it
                dp[i] = Math.min(dp[i], dp[i+1]) + triangle.get(layer).get(i);
            }
        }
        return dp[0];
    }
}

你可能感兴趣的:(120. Triangle)