【Leetcode】120.三角形最小路径和 旧城等待, 2022-01-20 11:55 190阅读 0赞 # 题目 # 给定一个三角形,找出自顶向下的最小路径和。每一步只能移动到下一行中相邻的结点上。 例如,给定三角形: [ [2], [3,4], [6,5,7], [4,1,8,3] ] 复制代码 自顶向下的最小路径和为 11(即,2 + 3 + 5 + 1 = 11)。 说明: 如果你可以只使用 O(n) 的额外空间(n 为三角形的总行数)来解决这个问题,那么你的算法会很加分。 # 题解 # 这道题目和之前A过的杨辉三角差不多,一看就是动态规划。 动态规划最主要的是确定状态表达式。而要求在o(n)的空间复杂度来解决这个问题,最主要的是要想清楚,更新状态的时候,不破坏下一次计算需要用到的状态。 我们采用"bottom-up"的动态规划方法来解本题。 状态表达式为: dp\[j\] = min(dp\[j\], dp\[j+1\]) + triangle\[j\]; class Solution { public int minimumTotal(List<List<Integer>> triangle) { int row = triangle.size(); List<Integer> res = new LinkedList<>(triangle.get(row - 1)); for (int i = row - 2; i >= 0; i--) { List<Integer> currentRow = triangle.get(i); for (int j = 0; j < currentRow.size(); j++) { res.set(j, Math.min(res.get(j), res.get(j + 1)) + currentRow.get(j)); } } return res.get(0); } } 复制代码 # 热门阅读 # * [百度社招面试题——Redis实现分布式锁][Redis] * [【Leetcode】114. 二叉树展开为链表][Leetcode_114.] * [社招面试总结——算法题篇][Link 1] * [Redis中的集合类型是怎么实现的?][Redis 1] [Redis]: https://link.juejin.im?target=https%3A%2F%2Fmp.weixin.qq.com%2Fs%2F6_uJ03bMyY8HeUDeb4HxYQ [Leetcode_114.]: https://link.juejin.im?target=https%3A%2F%2Fmp.weixin.qq.com%2Fs%2F4IxEj0B_CUW6B46HrZQmdA [Link 1]: https://link.juejin.im?target=https%3A%2F%2Fmp.weixin.qq.com%2Fs%2Fg9RyWpDWfGCnvPvw4res4Q [Redis 1]: https://link.juejin.im?target=https%3A%2F%2Fmp.weixin.qq.com%2Fs%2FJG-el06-1ehDntF_E7h1hQ
还没有评论,来说两句吧...