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.
使用動態規劃法。當我們計算第i層的數到底層的最小和時,如果我們知道第i+1層的數到底層最小的和就好算了。即minsum[i][j]=triangle[i]+min(
minsum[i+1][j] , minsum[i+1][j+1] );從底層向頂層逐層計算,就能得到最終結果。
class Solution {
public:
int minimumTotal(vector<vector<int> > &triangle) {
int n = triangle.size();
int** dp = new int*[n];
for(int i=0;i<n;i++) {
dp[i] = new int[n];
}
for(int j=0;j<n;j++) {
dp[n-1][j] = triangle[n-1][j];
}
for(int i=n-2;i>=0;i--) {
for(int j=0;j<=i;j++) {
dp[i][j] = triangle[i][j] + (dp[i+1][j]<dp[i+1][j+1]?dp[i+1][j]:dp[i+1][j+1]);
}
}
int minSum = dp[0][0];
for(int i=0;i<n;i++) {
delete dp[i];
}
delete dp;
return minSum;
}
};
,因爲每次計算只會查詢下一層的計算結果,下下層及更後層的計算結果不會使用到,因此可以只開個大小爲n的一維數組就可以了。
class Solution {
public:
int minimumTotal(vector<vector<int> > &triangle) {
int n = triangle.size();
int* dp = new int[n];
for(int j=0;j<n;j++) {
dp[j] = triangle[n-1][j];
}
for(int i=n-2;i>=0;i--) {
for(int j=0;j<=i;j++) {
dp[j] = triangle[i][j] + (dp[j]<dp[j+1]?dp[j]:dp[j+1]);
}
}
int minSum = dp[0];
delete dp;
return minSum;
}
};