[LeetCode] Triangle

120. Triangle

Given a triangle array, return the minimum path sum from top to bottom.

For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
int n = triangle.size();
for(int i = 1; i < n; i++) {
triangle[i][0] += triangle[i-1][0];
for(int j = 1; j < i ; j ++) {
triangle[i][j] = triangle[i][j] + min(triangle[i-1][j], triangle[i-1][j-1]);
}
triangle[i][i] += triangle[i-1][i-1];
}
return *min_element(triangle[n-1].begin(), triangle[n-1].end());
}
};


Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/13/PS/LeetCode/triangle/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.