LeetCode 120 Triangle

The topics are as follows

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

thought process

When you see the title, pay attention to the sentence "Each step you may move to adjacent numbers on the row below.", which means that each step can only go to the adjacent numbers in the next layer.

At the beginning, I wanted to build an array d[i][j] from top to bottom, representing the minimum sum of the numbers reaching the i-th row and j column. Use two layers of for loops and then judge the minimum sum of the two related numbers on the previous layer of each number, and take the smaller plus itself as d (be careful not to exceed the bounds). Then I do this with a lot of judgment and I don't know what the meaning of the rules is.,,,

So we have to traverse from bottom to top in another way. The minimum sum of each position (adding from bottom to top) is equal to the smaller minimum sum of the two adjacent numbers in the lower layer, and it is accumulated directly from the penultimate row, so the state Transfer equation:

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

Then there is:

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];
    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325563626&siteId=291194637