Skip to content

Commit 9394f89

Browse files
authored
Update 9.动态规划.md
1 parent 8e4685c commit 9394f89

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

9.动态规划.md

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,56 @@
189189
}
190190
}
191191

192+
## 7.三角形最小路径和 top150
193+
194+
120.给定一个三角形 triangle ,找出自顶向下的最小路径和。
195+
196+
每一步只能移动到下一行中相邻的结点上。相邻的结点 在这里指的是 下标 与 上一层结点下标 相同或者等于 上一层结点下标 + 1 的两个结点。也就是说,如果正位于当前行的下标 i ,那么下一步可以移动到下一行的下标 i 或 i + 1 。
197+
198+
示例 1:
199+
200+
输入:triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
201+
输出:11
202+
解释:如下面简图所示:
203+
2
204+
3 4
205+
6 5 7
206+
4 1 8 3
207+
自顶向下的最小路径和为 11(即,2 + 3 + 5 + 1 = 11)。
208+
209+
思路:动态规划,因为每一行只依赖上一行的结果,因此使用两个数组即可,一个数组储存前一行的结果,一个数组储存当前结果。cur是当前结果,pre是前一行结果,num是当前行的值。
210+
- 最左边的元素:cur[0] = pre[0] + num[0];
211+
- 最右边的元素:cur[j] = pre[j-1] + num[j];
212+
- 中间的元素:cur[j] = min(pre[j-1],pre[j]) + num[j]
213+
214+
class Solution {
215+
public int minimumTotal(List<List<Integer>> triangle) {
216+
if (triangle == null || triangle.size() == 0 || triangle.get(0).size() == 0) return 0;
217+
int[][] dp = new int[2][triangle.size()]; // 只有两行因此只是两个数组
218+
dp[0][0] = triangle.get(0).get(0);
219+
for (int i = 1; i < triangle.size(); i++) {
220+
int cur = i % 2; // 当前结果的数组,奇偶交替使用
221+
int pre = 1 - cur; // 另一个就是前一行结果的数组
222+
List<Integer> curNums = triangle.get(i);
223+
int curLength = curNums.size();
224+
for (int j = 0; j < curLength; j++) {
225+
if (j == 0) { // 最左边的元素
226+
dp[cur][j] = dp[pre][j] + curNums.get(j);
227+
} else if (j == curLength - 1) { // 最右边的元素
228+
dp[cur][j] = dp[pre][j - 1] + curNums.get(j);
229+
} else {
230+
dp[cur][j] = Math.min(dp[pre][j - 1], dp[pre][j]) + curNums.get(j);
231+
}
232+
}
233+
}
234+
int result = Integer.MAX_VALUE;
235+
for(int i = 0; i < triangle.size(); i++){
236+
result = Math.min(result, dp[(triangle.size()-1)%2][i]);
237+
}
238+
return result;
239+
}
240+
}
241+
192242
# 矩阵路径
193243

194244
## 1. 矩阵的最小路径和 top100
@@ -273,6 +323,8 @@
273323
}
274324
}
275325

326+
327+
276328
# 数组区间
277329

278330
## 1. 数组区间和

0 commit comments

Comments
 (0)