-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path120. Triangle
More file actions
34 lines (23 loc) · 976 Bytes
/
120. Triangle
File metadata and controls
34 lines (23 loc) · 976 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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.
Input: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
Output: 11
Explanation: The triangle looks like:
2
3 4
6 5 7
4 1 8 3
The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above).
Input: triangle = [[-10]]
Output: -10
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
for(int level = size(triangle) - 2; level >= 0; level--) // start from bottom-1 level
for(int i = 0; i <= level; i++)
// for every cell: we could have moved here from same index or index+1 of next level
triangle[level][i] += min(triangle[level + 1][i], triangle[level + 1][i + 1]);
return triangle[0][0]; // lastly t[0][0] will contain accumulated sum of minimum path
}
};