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

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).


两种方法,一种是使用后根遍历的递归算法,一种是使用动态规划的方法。下面是C++代码(postOrder函数是递归算法,minimumTotal函数是非递归算法):

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


阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 东成电动工具价格表 电动工具价格表 巨大电动工具价格表 博士电动工具价格表 博世电动工具价格表 华丽电动工具价格表 东成电动工具价格表切割机 申恒电动工具价格表 波斯工具价格表 在线表单工具 表单工具 博世电动工具价格表180 修表工具套装 力剑电动工具价格表 泉有电动工具价格表 开表后盖工具 日立电动工具价格表 工具论 微课制作工具 汽车工具大全 汽车修复工具 汽车检测工具 汽车抛光工具 汽车防身工具 汽车五金工具 汽车测量工具 汽车维修常用工具 汽车钣金维修工具 汽车钣金需要的工具 洗车 工具 修车工具什么牌子比较好 自动工具车 工具车轮胎 二手工具车 工具车汽车大全价格 洗车工具什么牌子好 二手工具车交易市场 淘宝洗车工具 洗车工具一套多少钱 家庭洗车工具 洗车工具哪个好