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.
class Solution { public: int minimumTotal(vector<vector<int>>& triangle) { vector<int> dp; int height = triangle.size(); int i,j,minSum; dp.push_back(triangle[0][0]); for(i = 1; i < height; i++){ dp[0]=dp[0]+triangle[i][0]; for(j = 1; j < triangle[i].size()-1; j++){ dp[j] = min(dp[j-1],dp[j])+triangle[i][j]; //有问题,下一个循环的时候dp[j-1]被改变了 } dp.push_back(dp[j-1]+triangle[i][j]); } minSum = dp[0]; for(int i = 1; i<triangle[height-1].size(); i++) { if(dp[i] < minSum) minSum = dp[i]; } return minSum; } };
Result: Wrong Answer
Input:
[[-1],[-2,-3]]
Output:
-6
Expected:
-4
所以要从右往左改变dp:
class Solution { public: int minimumTotal(vector<vector<int>>& triangle) { vector<int> dp; int height = triangle.size(); int i,j,minSum; dp.push_back(triangle[0][0]); for(i = 1; i < height; i++){ dp.push_back(dp[triangle[i-1].size()-1]+triangle[i][triangle[i].size()-1]); for(j = triangle[i].size()-2; j >= 1; j--){ dp[j] = min(dp[j-1],dp[j])+triangle[i][j]; } dp[0]=dp[0]+triangle[i][0]; } minSum = dp[0]; for(int i = 1; i<triangle[height-1].size(); i++) { if(dp[i] < minSum) minSum = dp[i]; } return minSum; } };
原文:http://www.cnblogs.com/qionglouyuyu/p/4915386.html