Skip to content

Commit

Permalink
update triangle algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
zhgw01 committed May 27, 2014
1 parent c305bc9 commit aa3ebec
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
34 changes: 34 additions & 0 deletions LeetCode/Triangle.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,40 @@ void Triangle::test2()
}

int Triangle::minimumTotal(vector<vector<int> > &triangle)
{
size_t rows = triangle.size();

if (rows == 0) {
return 0;
}

vector<int> sums(rows, 0);

//Initialize column 0
sums[0] = triangle[0][0];

for (size_t row = 1; row < rows; ++row) {
sums[row] = sums[row - 1] + triangle[row][row];

for (size_t col = row - 1; col > 0 ; --col) {
sums[col] = min(sums[col - 1], sums[col]) + triangle[row][col];
}

sums[0] += triangle[row][0];
}

// find minium
int result = sums[0];
for(size_t i = 1; i < rows; ++i) {
if (sums[i] < result) {
result = sums[i];
}
}

return result;
}

int Triangle::minimumTotal2(vector<vector<int> > &triangle)
{
size_t numRows = triangle.size();
if (numRows <= 0) {
Expand Down
1 change: 1 addition & 0 deletions LeetCode/Triangle.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ class Triangle : public IRun
void test2();

int minimumTotal(vector<vector<int> > &triangle);
int minimumTotal2(vector<vector<int> > &triangle);
};

#endif /* defined(__LeetCode__Triangle__) */

0 comments on commit aa3ebec

Please sign in to comment.