【问题标题】:Understanding dynamic programming through a example通过一个例子理解动态规划
【发布时间】:2016-07-01 10:48:30
【问题描述】:

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

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

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

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

这是我尝试过的:

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

对不起,如果这听起来很基本,我知道我遗漏了一些东西。谁能指出它有什么问题?

【问题讨论】:

标签: java dynamic-programming memoization


【解决方案1】:

为了解决这个问题,让我们为f(r,c) 定义一个循环公式。可能有几个选项可以做到这一点,但让我们坚持你在代码中的内容。

  1. f(r, c) = 0 if r &gt;= m
  2. f(r, c) = 0 if c &gt;= n
  3. f(r, c) = 1 if r == m &amp;&amp; c == n
  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)-cell 到 (m-1, n-1)-cell 存在多少条路径?

【讨论】:

    猜你喜欢
    • 2011-05-15
    • 2016-06-18
    • 2016-12-26
    • 1970-01-01
    • 2011-06-17
    • 2014-08-08
    • 1970-01-01
    • 2015-05-17
    • 2018-08-08
    相关资源
    最近更新 更多