您的位置:首页 > 其它

leetcode_120 Triangle_动态规划

2016-10-11 22:16 393 查看
题目链接

题意:

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.


分析:

拿到题目我第一时间想到贪心算法。但是使用贪心,每行找到一个最小值,那么这些最小值的路径不一定满足相邻的条件。既然不能用贪心,那么考虑下面这个简单的问题:

[

[2],

[3,4],

]

那么,计算从顶到底的所有可能的路径的和。显然 2+3=5比2+4=6大,所以结果为5。为了下一行的计算方便,用一个vector sum来保存当前行的计算结果[5,6]。

第三行[6,5,7]。对于当前行中的每一个元素,除了首尾,只需要找到上一行中和当前元素相邻的2个元素的最小值,然后把这儿最小值加上当前元素并更新加到vector sum就可以了。不断进行下去,直到最后一行为止。这个过程可以看做一个很简单的动态规划。

当然,为了题目要求的O(n),我们只用一个vector sum来存储并更新,所以在操作的过程中我们还需用pre_num,current_num先记录好原先在vector sum[j]的值,因为这个在更新sum[j+1]的值的时候需要用到原先的sum[j],而不是已经计算更新的sum[j].

基于这种思想,我们当然可以从顶往下,或者从底往上。

AC代码:

class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {

int size = triangle.size();
if(size==0)
return 0;
vector<int> sum;
sum.push_back(triangle[0][0]);
int pre,cur;
for(int i=1;i<size;i++){
pre = sum[0];
sum[0]+=triangle[i][0];
for(int j=1;j<i;j++) {
cur = sum[j];
sum[j]= triangle[i][j]+(pre<sum[j]?pre:sum[j]);
pre = cur;
}
sum.push_back(pre+triangle[i][i]);
}
for(int g=1;g<size;g++){
sum[0]=sum[0]<sum[g]?sum[0]:sum[g];
}
return sum[0];

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息