Skip to content

Instantly share code, notes, and snippets.

@zhoutuo
Created February 26, 2013 21:53
Show Gist options
  • Save zhoutuo/5042595 to your computer and use it in GitHub Desktop.
Save zhoutuo/5042595 to your computer and use it in GitHub Desktop.
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).
class Solution {
public:
int minimumTotal(vector<vector<int> > &triangle) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> second = triangle[triangle.size() - 1];
for(int i = triangle.size() - 2; i >= 0; --i) {
vector<int> first = triangle[i];
for(int j = 0; j < first.size(); ++j) {
first[j] += min(second[j], second[j + 1]);
}
second = first;
}
return second[0];
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment