第十四周:[leetCode] 120. Triangle

来源:互联网 发布:股海网指标公式源码 编辑:程序博客网 时间:2024/06/05 07:54

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

解题思路:
按照题目叙述思路,自顶向下,这貌似是一道深度搜索题,遍历所有路径,通过比较找出长度最短的路径。其实不然,这与深度搜索有较大区别,1是路径长度确定,2是路径中的节点可随机访问,那么稍加思考,可以想到用自底向上的方法更加方便快捷。为了便于思考,可将输入triangle想象为如下结构:

[2]
[3,4]
[6,5,7]
[4,1,8,3]

解题方法就显而易见了,代码如下:

int minimumTotal(vector<vector<int>>& triangle) {    int n = triangle.size();    if (n == 0) return 0;    int len[n];    // 取triangle最底层的路径值    for (int i = 0; i < n; i++) {        len[i] = triangle[n - 1][i];    }    for (int row = n - 1; row > 0; row--) {        for (int list = 0; list < row; list--) {            // 比较得出自底向上到该节点的最短路径            len[list] = min(len[list], len[list + 1]) + triangle[row - 1][list];        }    }    return len[0];}
原创粉丝点击