题目描述
给定一个三角形,找出自顶向下的最小路径和。每一步只能移动到下一行中相邻的结点上。
例如,给定三角形:
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
自顶向下的最小路径和为 11(即,2 + 3 + 5 + 1 = 11)。
总结
SDC1&2:逆向思维,像堆积木一样自底向上
SC:递归,加了存储数组优化
Sample & Demo Code 1
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int[] min = new int[triangle.size()+1]; // !!!
for(int level = triangle.size()-1; level >= 0; level--) {
for(int i = 0; i <= level; i++)
min[i] = Math.min(min[i], min[i+1]) + triangle.get(level).get(i);
}
return min[0];
}
}
Sample & Demo Code 2
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int m = triangle.size();
int[][] res = new int[m][m];
List<Integer> last = triangle.get(m-1);
for(int i = 0; i < m; i++)
res[m-1][i] = last.get(i);
for(int i = m-2; i >= 0; i--) {
List<Integer> cur = triangle.get(i);
for(int j = 0; j <= i; j++) {
res[i][j] = Math.min(res[i+1][j], res[i+1][j+1]) + cur.get(j);
}
}
return res[0][0];
}
}
Sample Code
class Solution {
int row;
Integer[][] memo;
public int minimumTotal(List<List<Integer>> triangle) {
row = triangle.size();
memo = new Integer[row][row];
return helper(0,0, triangle);
}
private int helper(int level, int c, List<List<Integer>> triangle){
// System.out.println("helper: level="+ level+ " c=" + c);
if (memo[level][c]!=null)
return memo[level][c];
if (level==row-1){
return memo[level][c] = triangle.get(level).get(c);
}
int left = helper(level+1, c, triangle);
int right = helper(level+1, c+1, triangle);
return memo[level][c] = Math.min(left, right) + triangle.get(level).get(c);
}
}
作者:crsm
链接:https://leetcode-cn.com/problems/triangle/solution/di-gui-ji-yi-hua-sou-suo-zai-dao-dp-by-crsm/