`

Leetcode - Trianlge

 
阅读更多

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

Note:
Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.

public class Solution {
    // dp[i] = min(dp[i], dp[i - 1]) + num[i]
    public int minimumTotal(List<List<Integer>> triangle) {
        if (triangle == null || triangle.size() == 0 || triangle.get(0).size() == 0)
            return 0;
        int rows = triangle.size();
        int cols = triangle.get(rows - 1).size();
        int[] dp = new int[cols];
        dp[0] = triangle.get(0).get(0);
        for (int i = 1; i < rows; i++) {
            int lastPos = triangle.get(i).size() - 1;
            dp[lastPos] = dp[lastPos - 1] + triangle.get(i).get(lastPos);
            for (int j = lastPos - 1; j > 0; j--) {
                dp[j] = Math.min(dp[j], dp[j - 1]) + triangle.get(i).get(j);
            }
            dp[0] += triangle.get(i).get(0);
        }
        int min = Integer.MAX_VALUE;
        for (int j = 0; j < cols; j++) {
            if (min > dp[j])
                min = dp[j];
        }
        return min;
    }
    
    // dp[i][j] = min(dp[i - 1][j], dp[i - 1][j - 1]) + num[i][j]
    /*
    public int minimumTotal(List<List<Integer>> triangle) {
        if (triangle == null || triangle.size() == 0 || triangle.get(0).size() == 0)
            return 0;
        int rows = triangle.size();
        int cols = triangle.get(rows - 1).size();
        int[][] dp = new int[rows][cols];
        dp[0][0] = triangle.get(0).get(0);
        for (int i = 1; i < rows; i++) {
            for (int j = 0; j < triangle.get(i).size(); j++) {
                if (j > 0 && j < triangle.get(i).size() - 1) {
                    dp[i][j] = Math.min(dp[i - 1][j - 1], dp[i - 1][j]) + triangle.get(i).get(j);
                } else if (j == 0) {
                    dp[i][j] = dp[i - 1][j] + triangle.get(i).get(j);
                } else if (j == triangle.get(i).size() - 1) {
                    dp[i][j] = dp[i - 1][j - 1] + triangle.get(i).get(j);
                }
            }
        }
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < cols; i++) {
            if (dp[rows - 1][i] < min)
                min = dp[rows - 1][i];
        }
        return min;
    }
    */
}

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics