lintcode-109. Triangle
来源:互联网 发布:台达plc编程入门 编辑:程序博客网 时间:2024/06/17 06:55
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
Notice
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.
Example
两种方法,一种是使用后根遍历的递归算法,一种是使用动态规划的方法。下面是C++代码(postOrder函数是递归算法,minimumTotal函数是非递归算法):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).
class Solution {public: /* * @param triangle: a list of lists of integers * @return: An integer, minimum path sum */ int postOrder(vector<vector<int>> &t,int i, int j) { if(i>=t.size()-1) return t[i][j]; else { return t[i][j]+min(postOrder(t,i+1,j), postOrder(t,i+1,j+1)); } } int minimumTotal(vector<vector<int>> &t) { // return postOrder(triangle,0,0); for(int i=t.size()-1;i>0;--i) { for(int j=0;j<t[i].size()-1;++j) { t[i-1][j]+=min(t[i][j],t[i][j+1]); } } return t[0][0]; }};
蓝桥杯上有一道类似的题目,不过是求总和最大的路径,链接如下:
http://blog.csdn.net/richenyunqi/article/details/78888272
阅读全文