A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?

Above is a 3 x 7 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
题意:给出一个m*n的矩阵,机器人在矩阵的左上角,机器人只能向下、向右移动,问机器人从左上角移到右下角有多少条路径?
思路:动态规划的方法
用dp(x,y)表示机器人从(1,1)移到(x,y)的路径个数,因为机器人只能向下和向右移动,其状态转移方程为
dp(x,y) = dp(x - 1, y) + dp(x, y -1),其中dp(1,1) = 1,采用记忆化搜索,防止递归时的重复计算
代码如下
public class Solution {
private static final int N = 101;
private static final int[][] dp = new int[N][N];
public int uniquePaths(int m, int n) {
if (dp[m][n] != 0) return dp[m][n];
if (m == 1 && n == 1) return dp[m][n] = 1;
return dp[m][n] = (m > 1 ? uniquePaths(m - 1, n):0) + (n > 1 ? uniquePaths(m, n - 1) : 0);
}
}

本文介绍了一个经典的动态规划问题——寻找从网格左上角到右下角的所有唯一路径数量。通过递归公式dp(x,y)=dp(x-1,y)+dp(x,y-1)来解决该问题,并提供了详细的代码实现。
1053

被折叠的 条评论
为什么被折叠?



