Triangle [LeetCode]
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.
Solution:
1 class Solution { 2 public: 3 int minimumTotal(vector<vector<int> > &triangle) { 4 if(triangle.size() == 0) 5 return 0; 6 vector<int> totals; 7 for(int i = 0; i < triangle.size(); i ++) { 8 if(i == 0){ 9 totals.push_back(triangle[0][0]); 10 continue; 11 } 12 vector<int> new_total; 13 for(int j = 0; j < triangle[i].size(); j ++) { 14 int sum = 0; 15 if(j - 1 < 0) 16 sum = triangle[i][j] + totals[j]; 17 else if (j > totals.size() - 1) 18 sum = triangle[i][j] + totals[j - 1]; 19 else 20 sum = min(triangle[i][j] + totals[j - 1], triangle[i][j] + totals[j]); 21 22 new_total.push_back(sum); 23 } 24 totals = new_total; 25 } 26 27 int min_total = totals[0]; 28 for(int i = 1; i < totals.size(); i ++) { 29 if(totals[i] < min_total) 30 min_total = totals[i]; 31 } 32 return min_total; 33 } 34 };