120. Triangle 类别:动态规划 难度:medium
2016-12-26 16:30
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.
For example, given the following triangle
The minimum path sum from top to bottom is
11).
程序:
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
vector<vector<int>> dp;
dp.push_back(vector<int>(1,0));
dp[0][0] = triangle[0][0];
for(int i = 0;i < triangle.size() - 1;i++)
{
dp.push_back(vector<int>(i + 2,INT_MAX));
for(int j = 0;j < triangle[i].size();j++)
{
dp[i + 1][j] = min(dp[i + 1][j],dp[i][j] + triangle[i + 1][j]);
dp[i + 1][j + 1] = min(dp[i + 1][j + 1],dp[i][j] + triangle[i + 1][j + 1]);
}
}
int res = INT_MAX;
int n = triangle.size();
for(int i = 0;i < n;i++)
res = min(res,dp[n - 1][i]);
return res;
}
};
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).
程序:
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
vector<vector<int>> dp;
dp.push_back(vector<int>(1,0));
dp[0][0] = triangle[0][0];
for(int i = 0;i < triangle.size() - 1;i++)
{
dp.push_back(vector<int>(i + 2,INT_MAX));
for(int j = 0;j < triangle[i].size();j++)
{
dp[i + 1][j] = min(dp[i + 1][j],dp[i][j] + triangle[i + 1][j]);
dp[i + 1][j + 1] = min(dp[i + 1][j + 1],dp[i][j] + triangle[i + 1][j + 1]);
}
}
int res = INT_MAX;
int n = triangle.size();
for(int i = 0;i < n;i++)
res = min(res,dp[n - 1][i]);
return res;
}
};
相关文章推荐
- 62. Unique Paths 类别:动态规划 难度:medium
- 63. Unique Paths II 类别:动态规划 难度:medium
- 64. Minimum Path Sum 类别:动态规划 难度:medium
- 376. Wiggle Subsequence 类别:动态规划 难度:medium
- 413. Arithmetic Slices 类别:动态规划 难度:Medium
- 96. Unique Binary Search Trees 类别:动态规划 难度:medium
- 357. Count Numbers with Unique Digits 类别:动态规划 难度:medium
- 309. Best Time to Buy and Sell Stock with Cooldown 类别:动态规划 难度:medium
- 343. Integer Break 类别:动态规划 难度:medium
- 300. Longest Increasing Subsequence 类别:动态规划 难度:medium
- 70. Climbing Stairs 类别:动态规划 难度:easy
- 198. House Robber 类别:动态规划 难度:easy
- 121. Best Time to Buy and Sell Stock 类别:动态规划 难度:easy
- 435. Non-overlapping Intervals 类别:贪心算法 难度:medium
- 55. Jump Game 类别:贪心算法 难度:medium
- 399. Evaluate Division 难度:medium 类别:图
- 310. Minimum Height Trees 难度:medium 类别:图
- 134. Gas Station 类别:贪心算法 难度:medium
- 332. Reconstruct Itinerary 难度:medium 类别:图
- 279. Perfect Squares 类别:medium 难度:medium