leetcode 120. Triangle
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.
solution
动态规划
状态转移方程为
位置{i}处的最小值要么是左边来的要么是右边来的
dp[i]=min{dp[left], dp[right]}+nowLocation
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
int n = triangle.size();
int dp[n+1][n+1];
for(int i = 1; i <= n ;i++)
dp[1][i] = triangle[n-1][i-1];
for(int i = 2; i <= n; i++)
for(int j = 1; j <= n-i+1; j++)
{
dp[i][j] = (dp[i-1][j] < dp[i-1][j+1] ? dp[i-1][j] : dp[i-1][j+1]) + triangle[n-i][j-1];
}
return dp[n][1];
}