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]; } };