zoukankan      html  css  js  c++  java
  • LeetCode-Triangle

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

    class Solution {
    public:
        int minimumTotal(vector<vector<int> > &triangle) {
            int total=triangle.size();
            if(total==0)return 0;
            vector<int> sum;
            vector<int> temp;
            sum.resize(total);
            temp.resize(total);
            sum[0]=triangle[0][0];
            for(int i=1;i<total;i++){
                int j=0;
                temp[j]=sum[0]+triangle[i][0];
                j++;
                for(;j<triangle[i].size()-1;j++){
                    temp[j]=min(sum[j-1],sum[j])+triangle[i][j];
                }
                temp[j]=sum[j-1]+triangle[i][j];
                for(j=0;j<triangle[i].size();j++)
                {
                    sum[j]=temp[j];
                }
            }
            int min=sum[0];
            for(int i=1;i<total;i++){
                if(sum[i]<min){
                    min=sum[i];
                }
            }
            return min;
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            
        }
    };
    
  • 相关阅读:
    选择排序
    java面试题08
    java面试题07
    java面试题06
    java面试题05
    oop.1
    4
    3
    Struts1中actionform和action属于MVC哪一层
    mysql查询时间段的所有数据
  • 原文地址:https://www.cnblogs.com/superzrx/p/3322606.html
Copyright © 2011-2022 走看看