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, wheren is the total number of rows in the triangle.
给定一个三角矩阵 从最上层到最下层的距离最小,下层选择的数和上层选择的数必须是相邻的
思路:
这是一个典型的DP问题,如果设定dp[i][j]表示从最上层到当前元素的路径的最小值,那么到矩阵都被设置后,从最后一层中找到最小的即可。
只不过需要注意的是每一层的第一个元素和最后一个元素,因为这两个位置的相邻元素只有一个。初始化dp[0][0]为三角矩阵的第一个元素的值。
?
int Path(vector
>& triangle)
{
vector
> dp(triangle.size()); int i,j; int tmp; int min; for(i=0;i
> triangle(4); int i,j; srand(rand()%100000); for(i=1;i<=4;i++) triangle[i-1].assign(i,0); for(i=0;i
?