LeetCode题解 week5

来源:互联网 发布:java高级工程师技能 编辑:程序博客网 时间:2024/06/07 06:51

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

这道题如果从上往下走,可能性会相当的多,并不是一个好的选择,我们可以尝试从下往上走,将会更为明了。
我画一个图辅助理解示意:
示意图
从0开始算,一共有n层,每一层有n+1个数。从上往下看,这个三角形的可走路径十分类似于一个二叉树,每一次只能选择相邻的两个节点往下走。反过来说,从下往上看,就是每次选择相邻的两个数字,对应的向上的路径只有一个。
要使得最终的结果路径最短,也就是说要使每个子路径最短。要想找到到第0层的最短路径,也就是要找的到第1层的两个数的最短路径,然后比较到达第0层的路径的长度求最小值;也就是要先找找第2层的三个数的最短路径,将第2层的三个数分别与第1层的两个数有路径的相加、比较找到最小值……
所以我们可以我们利用一个数组result来存储从第n层到当前层各个“节点”的最短路径,从第n层开始,自己到自己的最短路径是自己的数本身,所以result中的值即为第n层各个数的值;之后计算第n-1层,第n层的相邻的两个节点对应第n-1层中的唯一确定的一个节点(也就是n-1层中的这个节点可以到达第n层的这两个相邻节点),所以使用
minresult[i],result[i+1])+triangle[n2][i]
来计算n-1层中唯一确定节点的最小值。利用循环求得从第n层到n-1层中每个节点的最短路径,再利用一重循环,从第n层→第n-1层→第n-2层→……→第1层→第0层,从而求出从顶部到底部的最短路径(最小值)。而最终的result[0]就是我们目标值。

参考代码如下:

class Solution {public:    int minimumTotal(vector<vector<int>>& triangle) {        int n = triangle.size();        int result[n];        for(int i = 0; i < n; i++)            result[i] = triangle[n-1][i];        for(int i = n-2; i >= 0; i--) {            for(int j = 0; j <= i; j++) {                int min = result[j];                if(result[j+1] < result[j])                    min = result[j+1];                result[j] = min + triangle[i][j];            }        }        return result[0];    }};
原创粉丝点击