Triangle

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.


此题可谓一波三折, 先贴一个本人的错误代码:

class Solution {
public:
    int minimumTotal(vector<vector<int> > &triangle) 
    {
        int row  = triangle.size();
        if(row==1)
            return triangle[0][0];
        int result[row];
        memset(result,0,sizeof(result));
        int i,j;
        int temp1,temp2;
        result[0] = result[1] = triangle[0][0];
        for(i=1;i<row;i++)
        {
            temp1 = result[0];
            temp2 = result[i-1];
            
            for(j=1;j<i;j++)
            {
                if(result[j-1]<result[j])
                    result[j] = result[j-1]+triangle[i][j];
                else
                    result[j] = result[j]+triangle[i][j];
            }
           result[0] = temp1 + triangle[i][0];
           result[i] = temp2 + triangle[i][i];
           
        }
        sort(result,result+row);
        return result[0];
    }
};
错误原因是, 在更新result[j]时,会对下一次的判断有影响. 因为下一次要用到restult[j-1]


正确的代码只是稍微修改了一下, 从后往前更新, 这样就避免了影响

class Solution {
public:
    int minimumTotal(vector<vector<int> > &triangle) 
    {
        int row  = triangle.size();
        if(row==1)
            return triangle[0][0];
        int result[row];
        memset(result,0,sizeof(result));
        int i,j;
        int temp1,temp2;
        result[0] = result[1] = triangle[0][0];
        for(i=1;i<row;i++)
        {
            temp1 = result[0];
            temp2 = result[i-1];
            
            for(j=i-1;j>=1;j--)
            {
                if(result[j-1]<result[j])
                    result[j] = result[j-1]+triangle[i][j];
                else
                    result[j] = result[j]+triangle[i][j];
            }
           result[0] = temp1 + triangle[i][0];
           result[i] = temp2 + triangle[i][i];
           
        }
        sort(result,result+row);
        return result[0];
    }
};



posted @ 2013-12-22 07:12  海滨银枪小霸王  阅读(137)  评论(0编辑  收藏  举报