Triangle
Oct 30 '12
6503 / 17796
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).
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.
从最后一层开始,看上面一层的相邻节点,上面一层的每个节点在下一层有两个相邻节点,选取小的加上。加到最后,就是p[0],就是返回值了。
class Solution {
public:
int minimumTotal(vector<vector<int> > &triangle) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int size = triangle.size();
vector<int> sum (size+1, 0);
while(size-- >0){
for(int i=0; i<=size; i++)
sum[i] = triangle[size][i] + ((sum[i] < sum[i+1]) ? sum[i] : sum[i+1]);
}
return sum[0];
}
};