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.
想当然就想到了递归解决,求出所有从第 0 层到第 n-1 层所有路径之和,然后得到最小路径,中间不管路径大小,均计算出来,超时;
代码如下:
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
if(triangle.empty())
return 0;
vector<int> resultTmp;
int result;
getAllResult(resultTmp, triangle, 0, 0, 0);
result = INT_MAX;
for(int i=0; i<resultTmp.size(); ++i)
{
cout<<resultTmp[i]<<' ';
if(result > resultTmp[i])
result = resultTmp[i];
}
cout<<endl;
return result;
}
void getAllResult(vector<int>& resultTmp, vector<vector<int>>& triangle, int cursum, int k, int little)
{
if(k == triangle.size())
{
resultTmp.push_back(cursum);
return;
}
if(k == 0)
{
cursum = triangle[0][0];
little = 0;
}
else
cursum += triangle[k][little];
getAllResult(resultTmp, triangle, cursum, k+1, little);
getAllResult(resultTmp, triangle, cursum, k+1, little+1);
}
};
只能动态规划了,考虑从下层到上层计算最短路径,可以发现每次求最短路径,贪心的计算结果,而上层一定可以选择到下次最短的路径。
代码如下:
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
if(triangle.empty())
return 0;
for(int i=triangle.size()-2; i>=0; --i)
for(int j=0; j<triangle[i].size(); ++j)
triangle[i][j] = triangle[i+1][j] < triangle[i+1][j+1] ? triangle[i+1][j] : triangle[i+1][j+1];
return triangle[0][0];
}
};