您的位置:首页 > 其它

[Leetcode 65] 120 Triangle

2013-07-16 01:25 281 查看
Problem:

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.

Analysis:

Basically, this is a simple dynamic programming problem. Start from the first level, at level i, computing the possible min length of each position at level i give the i-1 level. And after computing the last level, use find_min funnction to get the minimum value of the path. Besides, this solution is an online version. It can always give the current solution.

This time complexity is O(n) and the space complecity is O(n).

Code:

class Solution {
public:
int minimumTotal(vector<vector<int> > &triangle) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
for (int i=1; i<triangle.size(); i++) {

for (int j=0; j<i+1; j++) {
if (j == 0) //first in a row
triangle[i][0] += triangle[i-1][0];
else if (j == i) //last in a row
triangle[i][i] += triangle[i-1][i-1];
else // two choice & get smaller
triangle[i][j] += min(triangle[i-1][j-1], triangle[i-1][j]);
}
}

return find_min(triangle[triangle.size()-1]);
}

int min(int a, int b) {
return (a<b)? a : b;
}

int find_min(vector<int> v) {
int min = v[0];

for (int i=1; i<v.size(); i++) {
if (v[i] < min)
min = v[i];
}

return min;
}


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