题目描述:

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 is11(i.e.,2+3+5+1= 11).

Note:
Bonus point if you are able to do this using onlyO(n) extra space, wherenis the total number of rows in the triangle.

思路:

记f(i, j)为以(x, j)为根的最短路径和。

状态转移方程:f(i, j) = min{f(i+1, j), f(i+1, j+1)} + (i, j)。

实现:

class Solution {
public:
    int minimumTotal(vector<vector<int>>& triangle) {
        for (int i = triangle.size() - 2; i >= 0; i--)
        {
            for (int j = 0; j != (triangle[i].size()); j++)
                triangle[i][j] += min(triangle[i+1][j], triangle[i+1][j+1]);
        }
        
        return triangle[0][0];
    }
};

优质内容筛选与推荐>>
1、[IE编程] WebBrowser控件的多页面浏览(Tabbed Browsing)开发接口
2、chmod命令详细用法
3、JavaScript 原型,原型链,call,apply
4、Websocket原理
5、简单易学的数据图表


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号