Triangle <leetcode>

Source: Internet
Author: User

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 is11(I. e., 2 + 3 + 5 + 1 = 11 ).

Note:
Bonus Point if you are able to do this using onlyO(N) Extra space, whereNIs the total number of rows in the triangle.

 

Algorithm: The first thing that comes to mind is DFS, but the code that times out is as follows:

class Solution {public:    int  result;    int minimumTotal(vector<vector<int> > &triangle) {        result=0;        doit(triangle,0,0,0);        return result;    }    void doit(vector<vector<int>>  &triangle,int level,int key,int sum)    {        if(level==triangle.size())        {           if(sum>result)  result=sum;           }        if(level<triangle.size()-1)        {           doit(triangle,level+1,key,sum+triangle[level][key]);           doit(triangle,level+1,key+1,sum+triangle[level][key]);        }    }};

The dynamic planning algorithm found on the Internet requires the minimum sum of the path from layer I to the bottom layer, as long as the minimum path from layer I + 1 to the bottom layer is known, the Code is as follows:

class Solution {public:    int minimumTotal(vector<vector<int> > &triangle) {            int len=triangle.size();        if(len==0)  return -1;        if(triangle[len-1].size()!=len)  return -1;        int *temp=new int[len];        for(int i=0;i<len;i++)        {            temp[i]=triangle[len-1][i];        }        for(int i=len-2;i>=0;i--)        {            for(int j=0;j<=i;j++)            {                temp[j]=triangle[i][j]+min(temp[j],temp[j+1]);            }        }        return temp[0];    }   };

  

Triangle <leetcode>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.