zoukankan      html  css  js  c++  java
  • Leetcode:Triangle

    Decription:

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

    Note:
    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.

    分析:这丫就是一个动态规划题,根据上一层各个元素的最小和来计算下一层各个元素的和。 因为要用O(n)的空间解决,n是三角形行数

    ,其实就是最长一行的元素个数,这个空间主要是用来记录上一行各个元素和的最小值,要保证只用这一个数组,则需要将这一行元素从后

    往前处理,保证新产生的和值,不会覆盖到上一行。

    #define INF 0x3f3f3f3f
    class Solution {
    public:
        int minimumTotal(vector<vector<int> > &triangle) {
            int rownum = triangle.size();
            if(rownum==0) return 0;
            int *pathrec = new int[rownum];
            memset(pathrec,0,sizeof(pathrec));
            
            pathrec[0] = triangle[0][0];
            for(int i=1;i<rownum;i++)
            {
                int elenum = triangle[i].size();
                for(int j=elenum-1;j>=0;--j)
                {
                   int minval = INF;
                   if(j<triangle[i-1].size())
                    minval = min(minval,pathrec[j]+triangle[i][j]);
                
                   if(j-1>=0)
                    minval = min(minval,pathrec[j-1]+triangle[i][j]);
                    
                   pathrec[j] = minval;
                }
            }
            int minval = INF;
            for(int i=0;i<rownum;i++)
                minval = min(minval,pathrec[i]);
            return minval;
        }
    };
  • 相关阅读:
    Lucene in action 笔记 case study
    关于Restful Web Service的一些理解
    Lucene in action 笔记 analysis篇
    Lucene in action 笔记 index篇
    Lucene in action 笔记 term vector
    Lucene in action 笔记 search篇
    博客园开博记录
    数论(算法概述)
    DIV, IFRAME, Select, Span标签入门
    记一个较困难的SharePoint性能问题的分析和解决
  • 原文地址:https://www.cnblogs.com/soyscut/p/3787542.html
Copyright © 2011-2022 走看看