题目如下:
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?
62. Unique Paths
给定一个mxn的矩阵,一机器人从左上角grid[0][0]出发,该机器人只能向下走或者向右走,要到达终点右下角grid[m-1][n-1],问最多有多少种不同的走法。
这道题目是典型的动态规划问题,设当前机器人处在grid[x][y],则之前机器人可能是向右走或向下走到达grid[x][y],设机器人处在grid[i][j]时的走法个数为dp[i][j],则dp[i][j] = dp[i-1][j] + dp[i][j-1]。
此外还应考虑边界条件dp[i][0]==0和dp[0][j]==0。
实现代码如下:
class Solution { public int uniquePaths(int m, int n) { if (m <= 1 || n <= 1) { return 1; } int[][] dp = new int[m][n]; for (int i = 0; i < m; i++) { dp[i][0] = 1; } for (int j = 0; j < n; j++) { dp[0][j] = 1; } for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; } } return dp[m - 1][n - 1]; } }
- 本文固定链接: https://weiguangli.com/archives/440
- 转载请注明: lwg0452 于 Weiguang的博客 发表
捐 赠如果您觉得这篇文章有用处,请支持作者!鼓励作者写出更好更多的文章!
Pingback 引用通告: [LeetCode每日一题]63. Unique Paths II | 闪技博客