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. 13个Cat命令管理(显示,排序,建立)文件实例

    在Linux系统中,大多数配置文件.日志文件,甚至shell脚本都使用文本文件格式,因此,Linux系统存在着多种文本编辑器,但当你仅仅想要查看一下这些文件的内容时,可使用一个简单的命令-cat. c ...

  2. python在linux制作图形界面(snack)

    snack是一个用于在linux制作图形界面(GUI)的模块,该模块由c编写,而且redhat的系统都自带这个模块. 1.获取模块 虽然redhat系统会自带这个模块,但是直接去import snac ...

  3. wordpress mobile templates

    http://themeforest.net/category/wordpress/mobile http://themeforest.net/item/monolith-wp-theme-for-b ...

  4. Angular js总结

    之前看过一些angular js的相关技术文档,今天在浏览技术论坛的时候发现有问angular js是做什么用的? 于是有了一个想法,对于自己对angular js 的认知做一个总结. 总结: ang ...

  5. AForm — 模型驱动的自动化表单解决方案

    http://xiehuiqi220.github.io/AForm/doc/book/#

  6. 网站报错Access denied for user 'root'@'localhost' -问题排查续

    网站报错Access denied for user 'root'@'localhost' (using password: YES) 每次的挽救办法就是: /etc/init.d/mysqld st ...

  7. routes.IgnoreRoute("{resource}.axd/{*pathInfo}")作用

    {resource}.axd 表示后缀名为.axd所有资源 如webresource.axd{*pathInfo} 表示所有路径 作用:使路由系统忽略处理ASP.NET的Web资源文件(WebReso ...

  8. centos 5.x 升级openssl

    今日想在centos 5.2上面安装mysql 5.5.37,在make的时候提示: Linking C shared module adt_null.so [ 65%] Built target a ...

  9. linux相关办公软件汇总

    ubuntu pdf阅读器 FoxitReader_1.1.0_i386.deb ubuntu 下的PDF阅读器(超级好使) Ubuntu下的chm和PDF阅读器 ubuntu便签软件xpad sud ...

  10. MyEclipse中文乱码,编码格式设置,文件编码格式 总结

    一.设置新建常见文件的默认编码格式,也就是文件保存的格式.在不对MyEclipse进行设置的时候,默认保存文件的编码,一般跟简体中文操作系统(如windows2000,windowsXP)的编码一致, ...