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]

 1 /*
 2     REC, SOL 1:
 3     */
 4     public int minimumTotal1(List<List<Integer>> triangle) {
 5         if (triangle == null || triangle.size() == 0) {
 6             return 0;
 7         }
 8         
 9         int rows = triangle.size();
10         int[][] mem = new int[rows][rows];
11         for (int i = 0; i < rows; i++) {
12             for (int j = 0; j < rows; j++) {
13                 mem[i][j] = Integer.MAX_VALUE;
14             }
15         }
16         
17         return dfs(triangle, 0, 0, mem);
18     }
19     
20     public int dfs(List<List<Integer>> triangle, int row, int col, int[][] mem) {
21         if (mem[row][col] != Integer.MAX_VALUE) {
22             return mem[row][col];
23         }
24         
25         if (row == triangle.size() - 1) {
26             mem[row][col] = triangle.get(row).get(col);
27         } else {
28             int left = dfs(triangle, row + 1, col, mem);
29             int right = dfs(triangle, row + 1, col + 1, mem);    
30             mem[row][col] = triangle.get(row).get(col) + Math.min(left, right);
31         }
32         
33         return mem[row][col];
34     }
View Code

相关文章:

  • 2021-07-05
  • 2021-12-01
  • 2021-07-17
  • 2021-05-26
  • 2021-08-12
  • 2021-09-02
  • 2021-12-28
  • 2021-10-30
猜你喜欢
  • 2022-01-07
  • 2021-05-17
  • 2022-12-23
  • 2021-11-05
  • 2021-08-09
  • 2021-11-09
  • 2022-12-23
相关资源
相似解决方案