通过示例

时间:2016-03-15 19:45:53

标签: java dynamic-programming memoization

我刚开始学习dp并尝试使用相同的(https://leetcode.com/problems/unique-paths/

从leetcode解决这个问题

机器人位于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];
    }
}

很抱歉,如果这听起来很基本,我知道我错过了什么。任何人都可以指出它有什么问题吗?

1 个答案:

答案 0 :(得分:1)

要解决此问题,请为update bank2 set bank2.dealer = bank1.dealer from CustomerName bank1 join CustomerName bank2 on bank2.SSN = bank1.SSN and bank2.Bank = 2 and bank1.Bank = 1 定义循环公式。可能有几个选项可以做,但让我们坚持你的代码。

  1. f(r,c)
  2. f(r, c) = 0 if r >= m
  3. f(r, c) = 0 if c >= n
  4. f(r, c) = 1 if r == m && c == n
  5. 根据公式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]; } ,这意味着从(0,0) - 单元到(m-1,n-1) - 单元存在多少条路径?