您的位置:首页 > 编程语言 > C语言/C++

LeetCode -- 120. Triangle

2017-05-25 16:12 330 查看

题目:

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.

思路:

这道题有些难度,之前第一想法用从上到下的方法寻找最短路径,但是有点傻逼,用了贪心的思想,结果当然不对,没有AC;转念一想,这TM是DP啊,于是又是一顿写,还是不对,边界处理比较麻烦。参考了大佬的想法,从下往上计算路径,一次就AC了,思路很重要,事半功倍~

令 sz=triangle.size();

初始状态:

d[sz−1][i]=triangle[sz−1][i],0≤i≤sz−1;

状态转移方程:

d[i][j]=min(d[i+1][j],d[i+1][j+1])+triangle[i][j],0≤j≤i≤sz−2;

d[0][0]即为最短路径。

C++代码如下:

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

for(int i = sz-2; i>=0;i--)
{
for(int j=0;j<=i;j++)
{
d[i][j] = min(d[i+1][j], d[i+1][j+1]) + triangle[i][j];
}
}

return d[0][0];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode c-c++