給定一個三角形,找出自頂向下的最小路徑和。每一步只能移動到下一行中相鄰的結點上。面試
例如,給定三角形:算法
[
[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);
}
}
複製代碼