原题链接:120. Triangle
【思路】
与以往处理杨辉三角形的方式不同,本题是从下往上递归处理。建立一个 dp 数组,每一行的最小和。以[[2],[3,4],[5,6,7]]为例,dp 的过程如下:

public class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int[] dp = new int[triangle.size()+1];
for(int i = triangle.size() - 1; i >= 0; i--)
for(int j = 0; j < triangle.get(i).size(); j++)
dp[j] = Math.min(dp[j], dp[j+1]) + triangle.get(i).get(j);
return dp[0];
}
}
43 / 43 test cases passed. Runtime: 5 ms Your runtime beats 56.63% of javasubmissions.
【补充】
同样的动归,采用深度优先,很容易想到用递归法,但是这种方法在数据量很大时超时了:
public int minimumTotal(List<List<Integer>> triangle) {
return findMinPath(triangle, 0, Integer.MAX_VALUE, 0, 0);
}
public int findMinPath(List<List<Integer>> triangle, int curSum, int min, int index, int level) {
curSum += triangle.get(level).get(index);
if (level == triangle.size() - 1)
return Math.min(min, curSum);
return Math.min(findMinPath(triangle, curSum, min, index, level + 1),
findMinPath(triangle, curSum, min, index + 1, level + 1));
}