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.
class Solution {
public:
int minimumTotal(vector<vector<int> > &triangle) {
int sizeX = triangle.size();
if(sizeX == 0)
return 0;
int sizeY = triangle[sizeX-1].size();
vector<int> cur(sizeY);
for(int x = sizeX - 1; x >=0; x--)
{
for(int y = 0; y < triangle[x].size(); y++)
{
if(x == sizeX - 1)
{
cur[y] = triangle[x][y];
}
else
{
cur[y] = std::min(cur[y], cur[y+1]) + triangle[x][y];
}
}
}
return cur[0];
}
};
Round 2:
class Solution {
public:
int minimumTotal(vector<vector<int> > &triangle) {
if(triangle.size() == 0)
return 0;
int sums[triangle[triangle.size()-1].size()] = {0};
for(int i = triangle.size()-1; i >=0; i--)
for(int j = 0; j <= i; j++)
{
if(i == triangle.size()-1)
{
sums[j] = triangle[i][j];
}
else
{
sums[j] = triangle[i][j] + std::min(sums[j], sums[j+1]);
}
}
return sums[0];
}
};