题目:
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) {
vector<vector<int>> dp;
dp.push_back(vector<int>(1,0));
dp[0][0] = triangle[0][0];
for(int i = 0;i < triangle.size() - 1;i++)
{
dp.push_back(vector<int>(i + 2,INT_MAX));
for(int j = 0;j < triangle[i].size();j++)
{
dp[i + 1][j] = min(dp[i + 1][j],dp[i][j] + triangle[i + 1][j]);
dp[i + 1][j + 1] = min(dp[i + 1][j + 1],dp[i][j] + triangle[i + 1][j + 1]);
}
}
int res = INT_MAX;
int n = triangle.size();
for(int i = 0;i < n;i++)
res = min(res,dp[n - 1][i]);
return res;
}
};