关于Java:通过示例了解动态编程

Understanding dynamic programming through a example

我刚刚开始学习dp,并尝试使用相同的(https://leetcode.com/problems/unique-paths/)从leetcode解决此问题。

机器人位于m x n网格的左上角(在下图中标记为"开始")。

机器人只能在任何时间点上下移动。机器人正在尝试到达网格的右下角(在下图中标记为"完成")。

有多少个可能的唯一路径?

enter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class Solution {
public int uniquePaths(int m, int n) {
    int [][] grid = new int[m][n];
    int [][] memo = new int[m][n];
    return uniquePathsHelper(grid,m,n,memo);
}

public int uniquePathsHelper(int [][] grid, int row,int col,int[][]memo){
    if(row>grid.length-1 || col>grid[0].length-1) return -1;
    if(row == grid.length-1 && col == grid[0].length-1) return 0;
    if(memo[row][col]!=0) return memo[row][col];

    if(col == grid[0].length-1) memo[row][col] = uniquePathsHelper(grid,row+1,col,memo)+1;
    if(row == grid.length-1) memo[row][col] = uniquePathsHelper(grid,row,col+1,memo)+1;
    // int rowInc = Integer.MIN_VALUE;
    // int colInc = Integer.MIN_VALUE;
    // if(row<grid.length-1) rowInc =  uniquePathsHelper(grid, row+1,col,memo);
    // if(col<grid.length-1) colInc = uniquePathsHelper(grid,row,col+1,memo);


    // if(row == grid.length-1 || col == grid[0].length-1) return 1;

    // if(row<grid.length-1) return 2;
    // if(col<grid[0].length-1) return 2;

    if(col< grid[0].length-1 && row < grid.length-1) memo[row][col] = memo[row+1][col] + memo[row][col+1];
    System.out.println("Memo["+row+"]["+col+"] ="+memo[row][col]);
    return memo[0][0];
    }
}

抱歉,这听起来很基础,我知道我遗漏了一些东西。谁能指出这是怎么回事?


要解决此问题,请为f(r,c)定义一个递归公式。可能有几种选择可以做到,但请坚持使用代码中的内容。

  • f(r, c) = 0 if r >= m
  • f(r, c) = 0 if c >= n
  • f(r, c) = 1 if r == m && c == n
  • f(r, c) = f(r + 1, c) + f(r, c + 1)
  • 根据公式uniquePathsHelper会是什么样?

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    // actually we don't need grid at all.
    // assume that we have m rows and n cols, m and n are global variables
    public int uniquePathsHelper(int row, int col, int[][] memo) {
        // 1-st and 2-d formulas
        if(row >= m || col >= n) return 0;
        // 3-d formula
        if(row == m - 1 && col == n - 1) return 1;

        if(memo[row][col] != 0) {
            // 4-th formula
            memo[row][col] = uniquePathsHelper(row, col + 1, memo) +
                uniquePathsHelper(row + 1, col, memo);
        }
        return memo[row][col];
    }

    要获得答案,只需调用uniquePathsHelper(0, 0, memo),这意味着从(0,0)单元到(m-1,n-1)单元有多少条路径?