LeetCode: Triangle 解题报告

Triangle

Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.

For example, given the following triangle
[
     [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).

Note:
Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.

SOLUTION 1:

使用DFS 加记忆矩阵的解法.

mem[i][j]表示第i行第j列的解。它的解可以由下一行推出:mem[i][j] = mem[i+1][j] + mem[i+1][j+1]

 /*
REC, SOL 1:
*/
public int minimumTotal1(List<List<Integer>> triangle) {
if (triangle == null || triangle.size() == 0) {
return 0;
} int rows = triangle.size();
int[][] mem = new int[rows][rows];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < rows; j++) {
mem[i][j] = Integer.MAX_VALUE;
}
} return dfs(triangle, 0, 0, mem);
} public int dfs(List<List<Integer>> triangle, int row, int col, int[][] mem) {
if (mem[row][col] != Integer.MAX_VALUE) {
return mem[row][col];
} if (row == triangle.size() - 1) {
mem[row][col] = triangle.get(row).get(col);
} else {
int left = dfs(triangle, row + 1, col, mem);
int right = dfs(triangle, row + 1, col + 1, mem);
mem[row][col] = triangle.get(row).get(col) + Math.min(left, right);
} return mem[row][col];
}

SOLUTION 2:

ref: http://blog.****.net/imabluefish/article/details/38656211

动态规划的题目

我们可以轻松将上面的修改为DP.

并且,为了减少内存使用量,使用一维DP即可。

f[j] 表示下一行第j列某点到最后底部的最短值。因为我们只需要下一行的这个值,所以我们使用一行的DP memory即可完成任务。

第一步: 先计算出最后一排的最短值,实际上就是这一排本身的值。
第二步:From bottom to up, 每一层的最短值只需要把自身值加上,并且取下层的左右邻接点的最小值。

 /*
DP, SOL 2:
*/
public int minimumTotal(List<List<Integer>> triangle) {
if (triangle == null || triangle.size() == 0) {
return 0;
} int rows = triangle.size();
int[] D = new int[rows]; for (int i = rows - 1; i >= 0; i--) {
// 注意:边界条件是 j <= i
for (int j = 0; j <= i; j++) {
if (i == rows - 1) {
D[j] = triangle.get(i).get(j);
} else {
D[j] = triangle.get(i).get(j) + Math.min(D[j], D[j + 1]);
}
}
} return D[0];
}

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/dp/MinimumTotal.java

上一篇:SELinux app权限配置


下一篇:一篇 JPA 总结