Triangle
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问题。bottom up.通过重用sum数组,使得空间达到O(n).
sum[i][j] = min(sum[i-1][j-1],sum[i-1][j]) + triangle[i][j];
j = 0/ j = i特殊情况。
int minimumTotal(vector<vector<int> > &triangle) { // Start typing your C/C++ solution below // DO NOT write int main() function if(triangle.empty()) return 0; int rows = triangle.size(); vector<int> sum(rows); sum[0] = triangle[0][0]; int prev,temp; for(int i=1;i<rows;i++) { prev = sum[0]; sum[0]+=triangle[i][0]; for(int j=1;j<i;j++) { temp = sum[j]; sum[j] = (prev>temp?(temp+triangle[i][j]):(prev+triangle[i][j])); prev = temp; } sum[i] = prev + triangle[i][i]; } int minSum = sum[0]; for(int i=1;i<rows;i++) { if(sum[i]<minSum) minSum = sum[i]; } return minSum; }