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

思考过程

看到题目注意一句话“Each step you may move to adjacent numbers on the row below.”,就是说每一步只能往下一层中相邻的数字走。

一开始想从上到下建立一个数组d[i][j],表示到达第i行j列的数字的最小和。用两层for循环然后判断每个数字上一层的两个相关数字的最小和,取较小的加上本身作为d(注意不能越界)。然后这么做多了很多判断以及不知道动规的意义何在,,,

所以得换个思路从下往上遍历,每个位置的最小和(从下往上加)等于其下层相邻两个数字之中较小的最小和,直接从倒数第二行开始累加,于是状态转移方程:

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

然后有:

class Solution {
public:
    int minimumTotal(vector<vector<int>>& triangle) {
        for(int i = triangle.size()-2; i >= 0; i--){
            for(int j = 0; j < triangle[i].size();j++){
                triangle[i][j]+=min(triangle[i+1][j+1], triangle[i+1][j]);
            }
        }
        return triangle[0][0];
    }
};

猜你喜欢

转载自blog.csdn.net/bkjs626/article/details/78418605
今日推荐