题目
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.
典型的dp问题。
设第i行第j个位置的数为d[i][j],到第i行第j个位置的最小路径总长度len[i][j]=min(len[i-1][j-1],len[i-1][j])+d[i][j],
由底(三角形的顶部)向上(三角形底部)计算递推即可。
由于只有上一行信息有用,因此在每行计算完毕后即可清除上一行的记录len[i-1][],从而使空间开销为O(n)。
代码:
(偷了个懒,如果使用两个一维数组或vector替代num效率会更高些)
class Solution {
public:
int minimumTotal(vector<vector<int> > &triangle) {
if(triangle.empty())
return 0;
vector<vector<int>> num(triangle.size(),vector<int>()); //记录到达相应位置的最小和
num[0].push_back(triangle[0][0]);
for(int i=1;i<triangle.size();i++) //dp
{
num[i].push_back(num[i-1][0]+triangle[i][0]);
for(int j=1;j<triangle[i].size()-1;j++)
num[i].push_back(min(num[i-1][j-1],num[i-1][j])+triangle[i][j]);
num[i].push_back(num[i-1].back()+triangle[i].back());
num[i-1].clear();
}
int min=num[triangle.size()-1][0]; //寻找底部的最小值
for(int i=1;i<triangle.size();i++)
if(min>num[triangle.size()-1][i])
min=num[triangle.size()-1][i];
return min; //返回最小值
}
};