给定一个三角形,找出自顶向下的最小路径和。每一步只能移动到下一行中相邻的结点上。面试
例如,给定三角形:算法
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
复制代码
自顶向下的最小路径和为 11(即,2 + 3 + 5 + 1 = 11)。bash
说明:分布式
若是你能够只使用 O(n) 的额外空间(n 为三角形的总行数)来解决这个问题,那么你的算法会很加分。ui
这道题目和以前A过的杨辉三角差很少,一看就是动态规划。 动态规划最主要的是肯定状态表达式。而要求在o(n)的空间复杂度来解决这个问题,最主要的是要想清楚,更新状态的时候,不破坏下一次计算须要用到的状态。 咱们采用"bottom-up"的动态规划方法来解本题。spa
状态表达式为: dp[j] = min(dp[j], dp[j+1]) + triangle[j];code
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);
}
}
复制代码