1.题目描述

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

2.解法分析

此题最简单的想法就是一个深度搜索,将所有可能的路径全部找出来,比较它们的和,于是有了如下的代码:

class Solution {

public:

    int minimumTotal(vector<vector<int> > &triangle) {

        // Start typing your C/C++ solution below

        // DO NOT write int main() function

        //by areslipan@163.com

        int minTotal= 0;

        

        for(int i = 0;i<triangle.size();++i)

        {

            minTotal+=triangle[i][0];

        }

        triangleHeight = triangle.size();

        int depth = 1;

        int curSum = 0;

        

        minnum(triangle,minTotal,1,0,curSum);

        

        return minTotal;

        

    }

   

    void minnum(vector<vector<int>> &triangle,int & minTotal,int depth,int loc,int &curSum)

    {

    

        curSum+=triangle[depth-1][loc];

        if(depth == triangleHeight)

        {

            minTotal = minTotal<curSum?minTotal:curSum;return;

        }

        

        minnum(triangle,minTotal,depth+1,loc,curSum);

        curSum -= triangle[depth][loc];

        minnum(triangle,minTotal,depth+1,loc+1,curSum);

        curSum -= triangle[depth][loc+1];

    }

     private:

    int triangleHeight;

    

};

 

在小数据集上运行良好,但是大数据集上就不行了,归根结底,深度遍历一方面有重复计算,一方面有递归消耗,再加上是个O(N2)的算法,必定会很慢,不过深度遍历的算法很直观,可以作为进一步分析的基础。既然知道深度搜索不行,那么该怎么办呢,我们发现,其实这个三角是有很强的最优子结构的,分析如下:

如果最短路径通过第i层(最上一层为0层,第一个元素标号为0)的第j个元素,那么必然有最短路径通过第i层的第j-1或者第j个元素,这种二选一的情形是由题意限定的,对于每一层的首尾需特殊处理,如果最短路径通过i层的首尾元素,说明最优路径在上一层的节点已经确定。于是,若已知截止于第i-1层的各个元素的最短路径和SUMi-1(SUM为长度为i的数组),那么截止于第i层的最短路径和SUMi的每个元素可以按照如下公式计算:

  • SUMi[j] = min(SUMi-1[j-1],SUMi-1[j]) +triangle[i][j]      若 j>0且j<i
  • SUMi[0] = SUMi-1[0]+triangle[0][0];
  • SUMi[i]  =SUMi-1[i-1] +triangle[i][i];

于是有了以下的代码:

class Solution {

public:

    int minimumTotal(vector<vector<int> > &triangle) {

        // Start typing your C/C++ solution below

        // DO NOT write int main() function

        //areslipan@163.com

        

        int triangleHeight = triangle.size();

        if(triangleHeight==0)return 0;

        

        //申请一个长度为n的辅助空间,作为动态规划的备忘表

        //备忘表被循环利用,第i个循环中只有前i个元素有意义,存放的是遍历到第i层的最佳路径对应的最小值

        vector<int> mmtTable;

        mmtTable.assign(triangleHeight,0);

        mmtTable[0]= triangle[0][0];

       

        int tmp = 0;

        for(int i = 1;i<triangleHeight;++i)

        {

            //特殊处理每一层的第一个元素,因为第一个元素的上一个节点一定是上一层的第一个元素

            int cur = mmtTable[0];

            mmtTable[0] = cur + triangle[i][0];

            

            //第i层的中间节点j可能上一层节点是第i-1层的j-1和j个节点

            for(int j=1;j<i;++j)

            {

                tmp = mmtTable[j];

                mmtTable[j] = min(cur,mmtTable[j])+triangle[i][j];

                cur = tmp;

            }

            

            //特殊处理每一层的最后一个元素,因为最后一个元素的上一个节点一定是上一层的最后一个元素

            mmtTable[i] = cur+triangle[i][i];

        }

        

        vector<int>::iterator iter;

        int minTotal = mmtTable[0];

        for(iter = mmtTable.begin();iter!=mmtTable.end();++iter)

        {

            if((*iter)<minTotal)minTotal = *iter;

        }

        

        return minTotal;

        

        

    }

};

leetcode—triangle的更多相关文章

  1. [LeetCode] Triangle 三角形

    Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent n ...

  2. leetcode — triangle

    /** * Source : https://oj.leetcode.com/problems/triangle/ * * * Given a triangle, find the minimum p ...

  3. [leetcode]Triangle @ Python

    原题地址:https://oj.leetcode.com/problems/triangle/ 题意: Given a triangle, find the minimum path sum from ...

  4. LeetCode - Triangle

    题目: Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjace ...

  5. LeetCode -- Triangle 路径求最小和( 动态规划问题)

    Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent n ...

  6. leetcode Triangle及其思考

    Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent n ...

  7. LeetCode Triangle 三角形(最短路)

    题意:给一个用序列堆成的三角形,第n层的元素个数为n,从顶往下,每个元素可以选择与自己最近的两个下层元素往下走,类似一棵二叉树,求最短路. [], [,4], [6,,7], [4,,8,3] 注意: ...

  8. LeetCode: Triangle 解题报告

    Triangle Given a triangle, find the minimum path sum from top to bottom. Each step you may move to a ...

  9. LeetCode 解题报告索引

    最近在准备找工作的算法题,刷刷LeetCode,以下是我的解题报告索引,每一题几乎都有详细的说明,供各位码农参考.根据我自己做的进度持续更新中......                        ...

随机推荐

  1. 007.Compiled

    Delphi property Compiled: Boolean read FCompiled; 类型:property 可见性:public 所在单元:System.RegularExpressi ...

  2. Excel导出-Epplus

    首先引入EPPlus.dll到你的项目bin文件中. Epplus引用的命名空间为 OfficeOpenXml 下面是对epplus一些用法的总结 一.创建一个空excel表格 //导出EXCEL设置 ...

  3. 刷漆(Codechef October Challenge 2014:Remy paints the fence)

    [问题描述] Czy做完了所有的回答出了所有的询问,结果是,他因为脑力消耗过大而变得更虚了:).帮助Czy恢复身材的艰巨任务落到了你的肩上. 正巧,你的花园里有一个由N块排成一条直线的木板组成的栅栏, ...

  4. 在图层上使用CATransform3D制做三维动画-b

    在UIView上,我们可以使用CGAffineTransform来对视图进行:平移(translation),旋转(Rotation),缩 放(scale),倾斜(Invert)操作,但这些操作是没有 ...

  5. pgrep 查询进程的工具

    pgrep 1:简介 pgrep 是通过程序的名字来查询进程的工具,一般是用来判断程序是否正在运行.在服务器的配置和管理中,这个工具常被应用,简单明了: 1:用法 #pgrep 参数选项 程序名 常用 ...

  6. ExtJS4.2学习(17)表单基本输入控件Ext.form.Field(转)

    鸣谢:http://www.shuyangyang.com.cn/jishuliangongfang/qianduanjishu/2013-12-11/189.html --------------- ...

  7. [Jquery] Jquery获取浏览器宽高的代码

    <script type="text/javascript"> $(document).ready(function() { alert($(window).heigh ...

  8. HTML中的转义字符

    HTML常用符号: 显示一个空格    < 小于 < <> 大于 > >& &符号 & &" 双引号 " &qu ...

  9. 为sublime text2 添加SASS语法高亮

    以前写CSS时,都是直接写样式,没有任何的第三方工具,后面发现越是面向大网站,越难管理,上次参加完携程UED大会后,发现SASS对于前端团队多人协作和站点代码维护上很有帮助,很多同学都开始用了,我还是 ...

  10. C#解压、压缩RAR文件

    using System; using System.Collections.Generic; using System.Text; using System.IO; using Microsoft. ...