通过一个例子了解动态规划

3

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

一个机器人位于 m x n 网格的左上角(下图中标记为“起点”)。

机器人只能向下或向右移动。机器人正在尝试到达网格的右下角(下图中标记为“终点”)。

有多少种可能的独特路径?

enter image description here

这是我的尝试:

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];
    }
}

抱歉,如果这听起来非常基础,我知道我错过了什么。有人能指出问题在哪里吗?

可能是在NxN网格中找到所有路径的算法的重复问题。 - aerin
1个回答

1
为了解决这个问题,让我们为f(r,c)定义一个递归公式。可能有几种方法可以做到这一点,但让我们坚持你在代码中所拥有的。
  1. 如果 r >= m,则 f(r, c) = 0
  2. 如果 c >= n,则 f(r, c) = 0
  3. 如果 r == m && c == n,则 f(r, c) = 1
  4. f(r, c) = f(r + 1, c) + f(r, c + 1)
根据这些公式,uniquePathsHelper会是什么样子?
// 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)单元格存在多少条路径?

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接