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.
Analyse: result[i][j] = min(result[i - 1][j - 1], result[i - 1][j]) + triangle[i][j];
Runtime: 8ms.
1 class Solution { 2 public: 3 int minimumTotal(vector<vector<int> >& triangle) { 4 if(triangle.size() == 0) return 0; 5 if(triangle.size() == 1) return triangle[0][0]; 6 7 vector<vector<int> > result; 8 result = triangle; 9 10 for(int i = 1; i < triangle.size(); i++){ 11 for(int j = 0; j <= i; j++){ 12 if(j == 0) result[i][j] = result[i - 1][0] + triangle[i][j]; 13 else if(j == i) result[i][j] = result[i - 1][j - 1] + triangle[i][j]; 14 else result[i][j] = min(result[i - 1][j - 1], result[i - 1][j]) + triangle[i][j]; 15 } 16 } 17 18 int n = triangle.size(); 19 int path = result[n - 1][0]; 20 for(int i = 1; i < n; i++){ 21 path = min(result[n - 1][i], path); 22 } 23 return path; 24 } 25 };