• 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;
        }
    };
  • 相关阅读:
    VS注释提示英文变中文的方法
    Windows 10安裝.net Framework 3.5出現0X800F0954錯誤
    NodeJS+NPM+Bower+Android环境安装配置
    复合索引
    高并发的核心技术-幂等的实现方案
    Redis初使用
    数据库SQL查找包含某列的所有table
    多线程中的wait与sleep到底谁释放了锁
    https配置
    iOS下的实际网络连接状态检测(转)
  • 原文地址:https://www.cnblogs.com/soyscut/p/3787542.html
Copyright © 2020-2023  润新知