题目

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

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

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)时的最小路径和,很容易看出:

0120. Triangle (M) - 图1%0A#card=math&code=dp%5Bi%5D%5Bj%5D%3Dtriangle%5Bi%5D%5Bj%5D%2Bmin%28dp%5Bi-1%5D%5Bj-1%5D%2C%5C%20dp%5Bi-1%5D%5Bj%5D%29%0A&id=tk46s)

对于空间复杂度0120. Triangle (M) - 图2#card=math&code=O%28N%29&id=CyYwx)的要求,可以使用滚动数组进行优化,这时候需要从最底层往最高层走,同样有公式:

0120. Triangle (M) - 图3%0A#card=math&code=dp%5Bj%5D%3Dtriangle%5Bi%5D%5Bj%5D%2Bmin%28dp%5Bj%5D%2C%5C%20dp%5Bj%2B1%5D%29%0A&id=J0g8V)

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


代码实现

Java

动态规划

  1. class Solution {
  2. public int minimumTotal(List<List<Integer>> triangle) {
  3. int[][] dp = new int[triangle.size()][triangle.size()];
  4. for (int i = triangle.size() - 1; i >= 0; i--) {
  5. for (int j = 0; j < triangle.get(i).size(); j++) {
  6. int curNum = triangle.get(i).get(j);
  7. if (i == triangle.size() - 1) {
  8. dp[i][j] = curNum;
  9. continue;
  10. }
  11. dp[i][j] = curNum + Math.min(dp[i + 1][j], dp[i + 1][j + 1]);
  12. }
  13. }
  14. return dp[0][0];
  15. }
  16. }

滚动数组优化

  1. class Solution {
  2. public int minimumTotal(List<List<Integer>> triangle) {
  3. int[] dp = new int[triangle.size()];
  4. for (int i = triangle.size() - 1; i >= 0; i--) {
  5. for (int j = 0; j < triangle.get(i).size(); j++) {
  6. int curNum = triangle.get(i).get(j);
  7. if (i == triangle.size() - 1) {
  8. dp[j] = curNum;
  9. continue;
  10. }
  11. dp[j] = curNum + Math.min(dp[j], dp[j + 1]);
  12. }
  13. }
  14. return dp[0];
  15. }
  16. }

JavaScript

  1. /**
  2. * @param {number[][]} triangle
  3. * @return {number}
  4. */
  5. var minimumTotal = function (triangle) {
  6. let ans = Number.MAX_SAFE_INTEGER
  7. const n = triangle.length
  8. const dp = new Array(n).fill(0)
  9. for (let i = 0; i < n; i++) {
  10. for (let j = i; j >= 0; j--) {
  11. if (j === 0) {
  12. dp[j] = triangle[i][j] + dp[j]
  13. } else if (j === i) {
  14. dp[j] = triangle[i][j] + dp[j - 1]
  15. } else {
  16. dp[j] = triangle[i][j] + Math.min(dp[j], dp[j - 1])
  17. }
  18. if (i === n - 1) ans = Math.min(ans, dp[j])
  19. }
  20. }
  21. return ans
  22. }