码迷,mamicode.com
首页 > 其他好文 > 详细

120. Triangle

时间:2018-01-05 15:22:30      阅读:90      评论:0      收藏:0      [点我收藏+]

标签:for   element   com   each   imu   body   pac   叠加   logs   

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

解析

  • 注意思路,从上往下,或者从下往上都可以,当遇见有覆盖的现象,考虑逆序处理。
// Triangle
class Solution_120 {
public:
    // top-down 
    int minimumTotal1(vector<vector<int>>& triangle) {
        vector<int> res(triangle.size(), triangle[0][0]);

        for (unsigned int i = 1; i < triangle.size(); i++)
            for (int j = i; j >= 0; j--) {
            if (j == 0)
                res[0] += triangle[i][j];
            else if (j == i)
                res[j] = triangle[i][j] + res[j - 1];
            else
                res[j] = triangle[i][j] + min(res[j - 1], res[j]);
            }
        return *min_element(res.begin(), res.end());
    }

    // bottom-up
    int minimumTotal2(vector<vector<int>>& triangle) {

        vector<int> res = triangle.back();
        for (int i = triangle.size() - 2; i >= 0; i--)
            for (unsigned int j = 0; j <= i; j++)
                res[j] = triangle[i][j] + min(res[j], res[j + 1]);
        return res[0];
    }

    int minimumTotal(vector<vector<int>>& triangle) {
        int row = triangle.size();
        
        if (row==0)
        {
            return 0;
        }
        if (row==1)
        {
            return triangle[0][0];
        }
        int ret = 0;
        

        vector<int> vec(triangle.size(), triangle[0][0]); //初始化

        for (int i = 1; i < row;i++) //当前行
        {
            for (int j = 0; j < triangle[i].size(); j++)
            {
                if (j==0)
                {
                    vec[j] = vec[j] + triangle[i][j];
                }else if (j==triangle[i].size()-1)
                {
                    vec[j] = vec[j-1] + triangle[i][j]; //bug 会叠加上一次改变的值 //变顺序啊!!!逆序
                }
                else
                {
                    vec[j] = triangle[i][j] + min(vec[j - 1], vec[j]);
                }
            }
        }
        return *min_element(vec.begin(), vec.end());
    }
};

题目来源

120. Triangle

标签:for   element   com   each   imu   body   pac   叠加   logs   

原文地址:https://www.cnblogs.com/ranjiewen/p/8203660.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!