我刚开始学习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];
}
}
抱歉,如果这听起来非常基础,我知道我错过了什么。有人能指出问题在哪里吗?