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) {
if(triangle.size()==0) return 0;
int n=triangle.size();
int m=triangle[0].size();
vector<int> temp=triangle[0];
for(int i=1;i<triangle.size();i++)
{
temp.push_back(0);
for(int j=0;j<triangle[i].size();j++)
{
if(j==0)
{
temp[j]+=triangle[i][j];
}
else if(j==triangle[i].size()-1)
{
temp[j]=triangle[i-1][j-1]+triangle[i][j];
}
else
{
temp[j]=(triangle[i][j]+triangle[i-1][j-1])>(triangle[i][j]+triangle[i-1][j])?
(triangle[i][j]+triangle[i-1][j]):(triangle[i][j]+triangle[i-1][j-1]); }
}
triangle[i]=temp;
}
sort(temp.begin(),temp.end());
return temp[0];
}
};