Appearance
0120-三角形的最小路径
https://leetcode.cn/problems/triangle/
给定一个三角形 triangle ,找出自顶向下的最小路径和。
每一步只能移动到下一行中相邻的结点上。相邻的结点 在这里指的是 下标 与 上一层结点下标 相同或者等于 上一层结点下标 + 1 的两个结点。也就是说,如果正位于当前行的下标 i ,那么下一步可以移动到下一行的下标 i 或 i + 1 。
示例 1:
输入:triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
输出:11
解释:如下面简图所示:
2
3 4
6 5 7
4 1 8 3
自顶向下的最小路径和为 11(即,2 + 3 + 5 + 1 = 11)。
示例 2:
输入:triangle = [[-10]]
输出:-10
提示:
1 <= triangle.length <= 200
triangle[0].length == 1
triangle[i].length == triangle[i - 1].length + 1
-104 <= triangle[i][j] <= 104
进阶:
你可以只使用 O(n) 的额外空间(n 为三角形的总行数)来解决这个问题吗?
基本思路
动态规划,依次从上往下求最优解 dp 表示最小路径和
2 3 4 6 5 7 4 1 8 3
其中 dp 要判断第一个和最后一个的值,因为他们只能由上面一个状态转移过来 dp[i,j] = min(dp[i-1,j-1],dp[i-1,j])
参考代码
csharp
public class Solution {
public int MinimumTotal(IList<IList<int>> triangle) {
int count = triangle.Count;
int[,] dp = new int[count,count];
dp[0,0] = triangle[0][0];
for(int i=1; i<triangle.Count; i++){
for(int j=0; j<triangle[i].Count;j++){
//Console.WriteLine("i={0},j={1},count:{2}",i,j,triangle[i].Count);
if(j == 0){
dp[i,j] = dp[i-1,j];
}
else if(j == triangle[i].Count - 1){
dp[i,j] = dp[i-1,j-1];
}
else{
dp[i,j] = Math.Min(dp[i-1,j-1],dp[i-1,j]);
}
dp[i,j]+=triangle[i][j];
}
}
//取最小值
int minSum = dp[count-1,0];
for(int i=1;i<count;i++){
minSum = Math.Min(minSum,dp[count-1,i]);
}
return minSum;
}
}
进阶思路:滚动数组
因为每次计算,只需要前面一个数组的值,所以可以使用 pre, cur 表示前面一次计算和此次计算的数组
参考代码
注意最后计算最小和的时候, minSum 取 pre的值,是考虑到只有一行的数据
csharp
public class Solution {
public int MinimumTotal(IList<IList<int>> triangle) {
int count = triangle.Count;
int[] pre = new int[count];
int[] cur = new int[count];
pre[0] = triangle[0][0];
for(int i=1; i<triangle.Count; i++){
for(int j=0; j<triangle[i].Count;j++){
if(j == 0){
cur[j] = pre[j];
}
else if(j == triangle[i].Count - 1){
cur[j] = pre[j-1];
}
else{
cur[j] = Math.Min(pre[j-1],pre[j]);
}
cur[j]+=triangle[i][j];
}
//赋值 pre = cur
for(int j=0;j<count;j++){
pre[j] = cur[j];
}
}
//取最小值
int minSum = pre[0];
for(int i=1;i<count;i++){
minSum = Math.Min(minSum,pre[i]);
}
return minSum;
}
}
进阶思路2:优化滚动数组
我们使用两个数组的原因是因为,第二次计算需要 pre[i-1] 和 pre[i]的值,如果直接从后面往前计算,是否就不需要两个数组了呢。 因为是计算 [i-1] 和 [i] 所以是可以的
参考代码
csharp
public class Solution {
public int MinimumTotal(IList<IList<int>> triangle) {
int count = triangle.Count;
int[] cur = new int[count];
cur[0] = triangle[0][0];
for(int i=1; i<count; i++){
for(int j=i; j>=0; j--){
if(j==i){//最后一个数
cur[j] = cur[j-1];
}
else if(j>0){
cur[j] = Math.Min(cur[j-1],cur[j]);
}
cur[j]+=triangle[i][j];
}
}
//取最小值
int minSum = cur[0];
for(int i=1;i<count;i++){
minSum = Math.Min(minSum,cur[i]);
}
return minSum;
}
}
AlgoPress