题意
给定一个三角形,找出自顶向下的最小路径和。每一步只能移动到下一行中相邻的结点上。
相邻的结点 在这里指的是 下标 与 上一层结点下标 相同或者等于 上一层结点下标 + 1 的两个结点。
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
The minimum path sum from top to bottom is 11
(i.e., 2 + 3 + 5 + 1 = 11).
解1
二维数组
// Runtime: 2 ms, faster than 76.85% of Java online submissions for Triangle.
public int minimumTotal(List<List<Integer>> triangle) {
if (triangle == null || triangle.size() == 0)
return 0;
int[][] dp = new int[triangle.size() + 1][triangle.size() + 1];
for (int i = 1; i <= triangle.size(); i++) {
for (int j = 1; j <= i; j++) {
if (j == i)
dp[i][j] = dp[i - 1][j - 1] + triangle.get(i - 1).get(j - 1);
else if (j == 1)
dp[i][j] = dp[i - 1][j] + triangle.get(i - 1).get(0);
else
dp[i][j] = Math.min(dp[i - 1][j - 1], dp[i - 1][j]) + triangle.get(i - 1).get(j - 1);
}
}
int rst = Integer.MAX_VALUE;
for (int i = 1; i < dp.length; i++)
rst = Math.min(rst, dp[dp.length - 1][i]);
return rst;
}
解2
和解1一样,优化一下,使用一维数组,因为要用到上一个循环的数据,所以从后往前遍历。
// Runtime: 2 ms, faster than 76.85% of Java online submissions for Triangle.
//Memory Usage: 39.3 MB, less than 16.65% of Java online submissions for Triangle.
public int minimumTotal2(List<List<Integer>> triangle) {
if (triangle == null || triangle.size() == 0)
return 0;
int[] dp = new int[triangle.size() + 1];
for (int i = 1; i <= triangle.size(); i++) {
for (int j = i; j >= 1; j--) {
if (j == i)
dp[j] = dp[j - 1] + triangle.get(i - 1).get(j - 1);
else if (j == 1)
dp[j] = dp[j] + triangle.get(i - 1).get(0);
else
dp[j] = Math.min(dp[j - 1], dp[j]) + triangle.get(i - 1).get(j - 1);
}
}
int rst = dp[1];
for (int i = 2; i < dp.length; i++)
rst = Math.min(rst, dp[i]);
return rst;
}