- 三角形最小路径和
题目:
给定一个三角形,找出自顶向下的最小路径和。每一步只能移动到下一行中相邻的结点上。
相邻的结点 在这里指的是 下标 与 上一层结点下标 相同或者等于 上一层结点下标 + 1 的两个结点。
例如,给定三角形:
[[2],[3,4],[6,5,7],[4,1,8,3]
]
自顶向下的最小路径和为 11(即,2 + 3 + 5 + 1 = 11)。
思路:
- 暴力法,递归,n层,left or right:2^n
- DP
a.重复性(分治) problem(i,j) = min(sub(i+1,j),sub(i+1,j+1)) + a[i,j]
b.定义状态数组 f[i,j]
c.DP方程:f[i,j] = min(f[i+1,j],f[i+1,j+1]) + a[i,j]
方法一:动态规划
public int minimumTotal(List<List<Integer>> triangle) {int[] A &#61; new int[triangle.size() &#43; 1];for (int i &#61; triangle.size() - 1;i >&#61; 0; i&#43;&#43;) {for(int j&#61; 0;j<triangle.get(i).size();j&#43;&#43;){A[j] &#61; Math.min(A[j],A[j&#43;1]) &#43; triangle.get(i).get(j);}}return A[0];}
方法二&#xff1a;递归 自顶向下
int row;public int minimumTotal_1(List<List<Integer>> triangle) {row &#61; triangle.size();return helper(0,0,triangle);}private int helper(int level, int c, List<List<Integer>> triangle) {System.out.println("helper : level&#61;" &#43; level &#43; "c &#61; " &#43; c);if (level &#61;&#61; row - 1){return triangle.get(level).get(c);}int left &#61; helper(level &#43; 1, c, triangle);int right &#61; helper(level &#43; 1, c &#43; 1 , triangle);return Math.min(left,right) &#43; triangle.get(level).get(c);}
方法三&#xff1a;自顶向下&#xff0c;记忆化搜索
int row;Integer[][] memo;public int minimumTotal_2(List<List<Integer>> triangle) {row &#61; triangle.size();memo &#61; new Integer[row][row];return helper(0,0,triangle);}private int helper(int level, int c, List<List<Integer>> triangle) {if (memo[level][c] !&#61; null){return memo[level][c];}if (level &#61;&#61; row - 1){return memo[level][c] &#61; triangle.get(level).get(c);}int left &#61; helper(level&#43;1,c,triangle);int right &#61; helper(level&#43;1,c&#43;1,triangle);return memo[level][c] &#61; Math.min(left,right) &#43; triangle.get(level).get(c);}
方法四&#xff1a;自底向上 DP
public int minimumTotal_3(List<List<Integer>> triangle) {int row &#61; triangle.size();int[] minlen &#61; new int[row &#43; 1];for (int level &#61; row - 1; level>&#61; 0; level&#43;&#43;) {for (int i &#61; 0; i <&#61; level; i&#43;&#43;) {minlen[i] &#61; Math.min(minlen[i],minlen[i&#43;1]) &#43; triangle.get(level).get(i);}}return minlen[0];}