0120. Triangle (M)

Triangle (M)

题目

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.


题意

给定一个三角形矩阵,求出从上到下的最小路径之和。

思路

动态规划:dp[i][j]代表从上到下走到(i, j)时的最小路径和,很容易看出:

[dp[i][j]=triangle[i][j]+min(dp[i-1][j-1], dp[i-1][j]) ]

对于空间复杂度(O(N))的要求,可以使用滚动数组进行优化,这时候需要从最底层往最高层走,同样有公式:

[dp[j]=triangle[i][j]+min(dp[j], dp[j+1]) ]

(实际操作中未使用滚动数组优化的动态规划也可以从下往上走,这样走到顶时得到的和就是最小路径和。)


代码实现

Java

动态规划

class Solution {
    public int minimumTotal(List<List<Integer>> triangle) {
        int[][] dp = new int[triangle.size()][triangle.size()];
        
        for (int i = triangle.size() - 1; i >= 0; i--) {
            for (int j = 0; j < triangle.get(i).size(); j++) {
                int curNum = triangle.get(i).get(j);

                if (i == triangle.size() - 1) {
                    dp[i][j] = curNum;
                    continue;
                }

                dp[i][j] = curNum + Math.min(dp[i + 1][j], dp[i + 1][j + 1]);
            }
        }
        
        return dp[0][0];
    }
}

滚动数组优化

class Solution {
    public int minimumTotal(List<List<Integer>> triangle) {
        int[] dp = new int[triangle.size()];
        
        for (int i = triangle.size() - 1; i >= 0; i--) {
            for (int j = 0; j < triangle.get(i).size(); j++) {
                int curNum = triangle.get(i).get(j);

                if (i == triangle.size() - 1) {
                    dp[j] = curNum;
                    continue;
                }

                dp[j] = curNum + Math.min(dp[j], dp[j + 1]);
            }
        }
        
        return dp[0];
    }
}

JavaScript

/**
 * @param {number[][]} triangle
 * @return {number}
 */
var minimumTotal = function (triangle) {
  let ans = Number.MAX_SAFE_INTEGER
  const n = triangle.length
  const dp = new Array(n).fill(0)

  for (let i = 0; i < n; i++) {
    for (let j = i; j >= 0; j--) {
      if (j === 0) {
        dp[j] = triangle[i][j] + dp[j]
      } else if (j === i) {
        dp[j] = triangle[i][j] + dp[j - 1]
      } else {
        dp[j] = triangle[i][j] + Math.min(dp[j], dp[j - 1])
      }

      if (i === n - 1) ans = Math.min(ans, dp[j])
    }
  }

  return ans
}
原文地址:https://www.cnblogs.com/mapoos/p/14685493.html