Leetcode: 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.
解法:
每步都有不同的选择,采用动态规划。自底向上,每步选择最优的结果。
代码如下:
int minimumTriangle(vector<vector<int>> &t) { int n = t.size(); vector<int> p(n+1, 0); while (n-- > 0) for(int i = 0; i <= n; ++i) p[i] = t[n][i] + ((p[i] < p[i+1]) ? p[i] : p[i+1]); return p[0]; } //p[i] 表示,在那一层中能选的最短的路径。
如果采用自顶向下的思路,那么需要将到达每层时的和利用p记录下来,然后选择下一步的p,这是p就不能为一维的向量了,因为在i层选择i+1层是,之间相互有重叠。
采用自底向上的思路时,一维度向量就可以了。