LeetCode120. Triangle（动态规划）

LeetCode120. Triangle（动态规划）

• Medium
• Accepted：172,497
• Submissions：447,076

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.

链接

https://leetcode.com/problems/triangle

题解

[
[2],          [11]
[3,4],   -->  [9,10]
[6,5,7],      [7,6,10]
[4,1,8,3]
]

代码

• Runtime: 8 ms, faster than 99.87% of C++ online submissions for Triangle.
• Memory Usage: 9.9 MB, less than 94.41% of C++ online submissions for Triangle.
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
int n = triangle.size();
for (int i = n - 2; i >= 0; --i)
{
int m = triangle[i].size();
for (int j = 0; j < m; ++j)
triangle[i][j] += min(triangle[i+1][j], triangle[i+1][j+1]);
}
return triangle[0][0];
}
};

The end.
2019年3月23日 星期六