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;
    }
};
原文地址:https://www.cnblogs.com/soyscut/p/3787542.html