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).
分析:题目的意思是给出一个三角形数组,求一个自上而下的最小的路径。采用动态规划的思想来分析,假设dp[i][j]表示到达triangle[i][j]时的最短路径,那么使用动态规划方法时它的初试值为:
接着找递推关系,从第二行开始:
如果是三角形的左边的点呢,就只能通过它的右斜上方的点过来,即dp[i][j] = dp[i-1][j]+ triangle[i][j];
如果是三角形的右边的点呢,就只能通过它的左斜上方的点过来,即dp[i][j] = dp[i-1][j-1] + triangle[i][j];
如果不是边界上的点,假设现在是triangle[i][j]点,那么它只能从它的上面相邻连个点过来,即triangle[i-1][j-1],triangle[i-1][j],换成递推的公式,就是:dp[i][j] = min(dp[i-1][j-1],dp[i-1][j]) + triangle[i][j];
最后,需要从最后一行中找出最小的一个值,代码如下:
Code(C++):
class Solution {
public:
int minimumTotal(vector<vector<int> > &triangle) {
int m = triangle.size();
if(m == 0) return 0;
vector<vector<int> > dp;
dp.resize(m);
dp[0].resize(1);
dp[0][0] = triangle[0][0];
for(int i = 1; i < m; i++) {
int n = triangle[i].size();
dp[i].resize(n);
for(int j = 0; j < n; j++){
if(j == 0) dp[i][j] = dp[i-1][j]+ triangle[i][j];
else if(j == n-1) dp[i][j] = dp[i-1][j-1] + triangle[i][j];
else {
dp[i][j] = min(dp[i-1][j-1],dp[i-1][j]) + triangle[i][j];
}
}
}
return getMin(dp[m-1]);
}
int getMin(vector<int> nums){
int n = nums.size();
if(n == 0) return 0;
int min = nums[0];
for(int i = 1; i < n; i++){
if(nums[i] < min)
min = nums[i];
}
return min;
}
};
原文地址:http://blog.csdn.net/dream_angel_z/article/details/46492259