您的位置:首页 > 其它

Triangle

2015-08-09 15:14 441 查看
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.

Have you met this question in a real interview? 

Yes

Example

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.
题目属于简单的DP问题,但是Note有要求,开辟的空间最多为O(n),n为层数。因为是三角形,所以i层的数的个数大于i - 1层的个数,那么可以分配一个第n层大小的数组,tmpMin[i]表示经过上几层到达n层的i点的最小路径值,这样到达最后一层就可以记录从最少一层到达最后一层个点的最小值,然后取最小值,作为整个三角形的最小值。对于每一层的一个点i,上一层与其相邻的是点i,i-1两个点,所以tmpMin[i]是上一层的min{tmpMin[i],
tmpMin[i - 1]},有了这个子问题描述之后,代码就好写了。但是注意一个细节,对于每一层的tmpMin[i]计算,应该从后向前,即for i = len - 1 ... 0,这样做是为了保证子问题中的tmpMin[i - 1]是上一层的,而不是当前层的。
class Solution {
public:
/**
* @param triangle: a list of lists of integers.
* @return: An integer, minimum path sum.
*/
int minimumTotal(vector<vector<int> > &triangle) {
// write your code here
int len = triangle.size();
if(len < 1)
return 0;
if(len == 1)
return triangle[0][0];
vector<int> tmpMin(len, 0);
for(int i = 0; i < len; ++i)
{
if(i == 0)
{
tmpMin[0] = triangle[0][0];
continue;
}

int tmpLen = triangle[i].size();
if(i > 0)
tmpMin[tmpLen - 1] = triangle[i][tmpLen - 1] + tmpMin[tmpLen - 2];

for(int j = tmpLen - 2; j >= 0; --j)
{
int tmp = tmpMin[j];
if(j > 0)
tmp = (tmp > tmpMin[j - 1]) ? tmpMin[j - 1] : tmp;
tmpMin[j] = tmp + triangle[i][j];
}
}

int min = INT_MAX;
for(int i = 0; i < len; ++i)
{
min = (min > tmpMin[i]) ? tmpMin[i] : min;
}

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