Understanding dynamic programming through a example
我刚刚开始学习dp,并尝试使用相同的(https://leetcode.com/problems/unique-paths/)从leetcode解决此问题。
机器人位于m x n网格的左上角(在下图中标记为"开始")。
机器人只能在任何时间点上下移动。机器人正在尝试到达网格的右下角(在下图中标记为"完成")。
有多少个可能的唯一路径?
这是我尝试的方法:
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]; } } |
抱歉,这听起来很基础,我知道我遗漏了一些东西。谁能指出这是怎么回事?
要解决此问题,请为
根据公式
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]; } |
要获得答案,只需调用