[LintCode/LeetCode] Triangle

411 查看

Problem

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

Notice

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.

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

第一种DP方法是很早之前写的,先对三角形两条斜边赋值,sum[i][0]sum[i][i]分别等于两条斜边上一个点的sum[i-1][0]sum[i-1][i-1]与当前点的和。
然后套用动规公式进行横纵坐标的循环计算所有点的path sum,再遍历最后一行的path sum,找到最小值即可。

Solution

DP:

public class Solution {
    public int minimumTotal(int[][] triangle) {
        int n = triangle.length;
        int[][] dp = new int[n][n];
        dp[0][0] = triangle[0][0];
        for (int i = 1; i < n; i++) {
            dp[i][0] = dp[i-1][0] + triangle[i][0];
            dp[i][i] = dp[i-1][i-1] + triangle[i][i];
        }
        for (int i = 1; i < n; i++) {
            for (int j = 1; j < i; j++) {
                dp[i][j] = Math.min(dp[i-1][j], dp[i-1][j-1]) + triangle[i][j];
            }
        }
        int res = dp[n-1][0];
        for (int i = 0; i < n; i++) {
            res = Math.min(res, dp[n-1][i]);
        }
        return res;
    }
}

Advanced DP:

public class Solution {
    public int minimumTotal(int[][] A) {
        int n = A.length;
        for (int i = n-2; i >= 0; i--) {
            for (int j = 0; j <= i; j++) {
                A[i][j] += Math.min(A[i+1][j], A[i+1][j+1]);
            }
        }
        return A[0][0];
    }
}