无意中看到别人博客上的这个题目,也来尝试解决下
题目原型:
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.
#include <iostream>
const int line = 4;
const int node_weight[line][line] =
{
{ 2 },
{ 3, 4 },
{ 6, 5, 7 },
{ 4, 1, 8, 3 }
/*
{ 2 },
{ 4, 3 },
{ 7, 5, 6 },
{ 4, 2, 3, 0 }
*/
};
int path_index[line][line] = { 0 };
void solve()
{
// path_index: 最后一行保存每条路径的总权重
for (int col = 0; col < line; ++col)
{
path_index[line - 1][col] = node_weight[line - 1][col];
}
// path_index: 其余行保存最短路径中下个节点的下标
for (int row = line - 2; row >= 0; --row)
{
for (int col = 0; col <= row; ++col)
{
if (path_index[line - 1][col] <= path_index[line - 1][col + 1])
{
path_index[row][col] = col;
path_index[line - 1][col] = node_weight[row][col] + path_index[line - 1][col];
}
else
{
path_index[row][col] = col + 1;
path_index[line - 1][col] = node_weight[row][col] + path_index[line - 1][col + 1];
}
}
}
// 打印最短路径的大小和最短路径
std::cout << "path length: " << path_index[line - 1][0] << std::endl;
std::cout << "path: " << node_weight[0][0];
for (int row = 1, col = path_index[0][0]; row < line; ++row)
{
std::cout << " -> " << node_weight[row][col];
col = path_index[row][col];
}
std::cout << std::endl;
}
int main(int argc, char * argv[])
{
solve();
return(0);
}