LeetCode 120. Triangle
2016-09-05 18:37
239 查看
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.
题目链接
题意:多行数据,从第一行到最后一行,每行选一个。求和的最小值。要求对于第i行第j个数据,那么它下面的一行(第i+1行)只能选择第j个或者第j+1个元素。
![](https://img-blog.csdn.net/20160905181357660)
动态规划的状态转移方程:f[ i, j ]=f[ i, j ]+ min { f[ i-1, j-1 ], f[ i-1, j ]}
从上往下遍历时,把 f 转换为一维数组会有问题。采用从下向上遍历。
状态转移方程变为:f[ i, j ]=f[ i, j ]+ min { f[ i+1, j ], f[ i+1, j+1]}
f[ j ]=f[ j ]+ min { f[ j ], f[ j+1 ]}
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.
题目链接
题意:多行数据,从第一行到最后一行,每行选一个。求和的最小值。要求对于第i行第j个数据,那么它下面的一行(第i+1行)只能选择第j个或者第j+1个元素。
动态规划的状态转移方程:f[ i, j ]=f[ i, j ]+ min { f[ i-1, j-1 ], f[ i-1, j ]}
从上往下遍历时,把 f 转换为一维数组会有问题。采用从下向上遍历。
状态转移方程变为:f[ i, j ]=f[ i, j ]+ min { f[ i+1, j ], f[ i+1, j+1]}
f[ j ]=f[ j ]+ min { f[ j ], f[ j+1 ]}
class Solution { public: int minimumTotal(vector<vector<int> >& triangle) { vector<int> minvec=triangle.back(); for(int layer=triangle.size()-2;layer>=0;layer--){ for(int j=0;j<=layer;j++) minvec[j]=triangle[layer][j]+min(minvec[j],minvec[j+1]); } return minvec[0]; } };
相关文章推荐
- Leetcode 120. Triangle
- LeetCode 120. Triangle
- [leetcode] 120. Triangle
- LeetCode解题报告 120. Triangle [medium]
- leetcode-120. Triangle
- 【LeetCode】120. Triangle
- leetcode 120. Triangle
- LeetCode 120. Triangle
- <LeetCode OJ> 120. Triangle
- [LeetCode]120. Triangle
- 120. Triangle【M】【95】【leetcode】
- LeetCode-120. Triangle
- [LeetCode] 120. Triangle
- LeetCode#120. Triangle
- 【LeetCode】120. Triangle (3 solutions)
- Leetcode-120. Triangle
- LeetCode 120. Triangle
- Leetcode 120. Triangle
- LeetCode - 120. Triangle - 思路详解 - C++
- LeetCode 120. Triangle 题解