您的位置:首页 > 其它

Triangle

2017-12-05 19:15 183 查看
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.

时间复杂度O(N),N表示triangle的元素个数,空间复杂度O(n),n表示最底层的元素个数。

class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
int minimumSum = 0;
if (triangle.size() >= 1)
{
int row = triangle.size() - 1, col = 0;
vector<int> minimumRow(triangle[row].size(), 0);
for (col = 0; col < triangle[row].size(); col++)
{
minimumRow[col] = triangle[row][col];
}

for (int row = triangle.size() - 2; row >= 0; row--)
{
for (int col = 0; col < triangle[row].size(); col++)
{
if (minimumRow[col] < minimumRow[col + 1])
{
minimumRow[col] = minimumRow[col] + triangle[row][col];
}
else
{
minimumRow[col] = minimumRow[col + 1] + triangle[row][col];
}
}
}
minimumSum = minimumRow[0];
}
return minimumSum;
}
};


为了更加深刻的理解DP的递归方案,下面提供了一种基于memo的recursive方案及相关测试代码。

#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

int getMinPathSum(vector<vector<int>> &triangle, int row)
{
static vector<int> minMemo(triangle.size());
int col = 0;
if (row == triangle.size() - 2)
{
for (col = 0; col < triangle[row].size(); col++)
{
minMemo[col] = min(triangle[row + 1][col], triangle[row + 1][col+1]) + triangle[row][col];
}
}
else
{
getMinPathSum(triangle, row + 1);
for (col = 0; col < triangle[row].size(); col++)
{
minMemo[col] = min(minMemo[col], minMemo[col + 1]) + triangle[row][col];
}
}
return minMemo[0];
}

int main(int argc, char * * argv, char * * env)
{
vector<int> row1 = { 2 };
vector<int> row2 = { 3, 4 };
vector<int> row3 = { 6, 5, 7 };
vector<int> row4 = { 4, 1, 8, 3 };
vector<vector<int>> triangle;
triangle.push_back(row1);
triangle.push_back(row2);
triangle.push_back(row3);
triangle.push_back(row4);
int mingPathSum = getMinPathSum(triangle, 0);
std::cout << "MinPathSum:" << mingPathSum << std::endl;
char ch;
scanf_s("%c", &ch);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Triangle leetcode 120