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]=min(dp[i-1][j],dp[i-1][j+1])+trangle[i][j];注意只有一个元素和0个元素的情况。
这样子的时间复杂度和空间复杂度都是O(n^2)。
代码:
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
int n=triangle.size();
if(n==0)
return 0;
else if(n==1)
return triangle[0][0];
int dp[n][n];
for(int i=n-1;i>=0;i--)
dp[n-1][i]=triangle[n-1][i];
for(int i=n-2;i>=0;i--)
for(int j=0;j<=i;j++)
dp[i][j]=min(dp[i+1][j],dp[i+1][j+1])+triangle[i][j];
return dp[0][0];
}
};
第二种解法大体上和第一种差不多,但是降低了空间复杂度。
但是很巧妙。用一个数组sum,初始化为最底层各个数的值,每计算一次就更新一次。
代码:
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
int n=triangle.size();
if(n==0)
return 0;
else if(n==1)
return triangle[0][0];
vector<int>sum=triangle[n-1];
for(int i=n-2;i>=0;i--)
{
for(int j=0;j<=i;j++)
sum[j]=min(sum[j],sum[j+1])+triangle[i][j];
}
return sum[0];
}
};