[LeetCode] 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).
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.
用从后往前更新的方法,就只需要O(n)的额外空间。
1 class Solution { 2 public: 3 int minimumTotal(vector<vector<int> > &triangle) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 if (triangle.size() == 0) 7 return 0; 8 9 vector<int> f(triangle[triangle.size()-1].size()); 10 11 f[0] = triangle[0][0]; 12 for(int i = 1; i < triangle.size(); i++) 13 for(int j = triangle[i].size() - 1; j >= 0; j--) 14 if (j == 0) 15 f[j] = f[j] + triangle[i][j]; 16 else if (j == triangle[i].size() - 1) 17 f[j] = f[j-1] + triangle[i][j]; 18 else 19 f[j] = min(f[j-1], f[j]) + triangle[i][j]; 20 21 int ret = INT_MAX; 22 for(int i = 0; i < f.size(); i++) 23 ret = min(ret, f[i]); 24 25 return ret; 26 } 27 };