题目链接:
https://leetcode.com/problems/triangle/description/
描述
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.
输入
输入一个二维数组,输出最小和。
输出
最小和。
样例输入
[[2],[3,4],[6,5,7],[4,1,8,3]] |
样例输出
11 |
算法思想:
动态规划。
dp[i][j]=⎧⎩⎨dp[i−1][j]+triangle[i][j]dp[i−1][j−1]+triangle[i][j]min(dp[i−1][j−1], dp[i−1][j])+triangle[i][j]i=0j=ii>0j>0
源代码
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
int sz = triangle.size(), sum = 0;
vector<int> vec;
for (int i = 0; i < sz; i++)
{
for (int j = 0; j <= i; j++)
{
if (i > 0 && j > 0 && j != i)
{
triangle[i][j] += min(triangle[i - 1][j - 1], triangle[i - 1][j]);
}
if (i > 0 && j == 0)
{
triangle[i][j] += triangle[i - 1][j];
}
if (i > 0 && j == i)
{
triangle[i][j] += triangle[i - 1][j - 1];
}
}
}
int ans = 9999999;
for (int i = 0; i < sz; i++)
{
if (ans > triangle[sz - 1][i])
ans = triangle[sz - 1][i];
}
return ans;
}
};