120. Triangle(Array; DP, WPS)
2015-10-27 20:10
309 查看
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
The minimum path sum from top to bottom is
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.
Result: Wrong Answer
Input:
[[-1],[-2,-3]]
Output:
-6
Expected:
-4
所以要从右往左改变dp:
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; } };
相关文章推荐
- Android设计模式系列-单例模式
- 一趟聚类
- #define详解
- COGS1532. [IOI2001]移动电话
- 如何判断一个已经写好的MFC程序是单文档还是多文档?
- 华而不实啊。哈哈哈。
- Apache访问控制
- 8.13**
- json传值
- Android设计模式—策略模式
- Oracle:Authid Current_User的使用
- 关于C++中的前置声明
- iOS开发技巧--点属性的小隐晦技巧
- 正规化方程Normal Equations解析
- suse linux rpm安装
- 解读Nodejs多核处理模块cluster
- linux 下常用的文件和目录操作命令(转)
- Android设计模式系列-组合模式
- 并查集基础
- 向MyEclipse添加Oracle数据库