Unique Paths
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 7 x 3 grid. How many possible unique paths are there?
Note: _m _and _n _will be at most 100.
Example 1:
Example 2:
Analysis
标准的二维动态规划问题
状态:dp[i][j]
- 从起点到达(i, j)的路径数目
状态转移方程: dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
- 左侧(i, j - 1)
和上方 (i - 1, j)
位置的路径之和,因为从左侧和上方到达(i, j)
均只有一种路径
初始条件: dp[i][0] = 1 (i = 0, ... m - 1)
, dp[0][j] = 1 (j = 0, ..., n - 1)
答案:dp[m - 1][n - 1]
即终点位置
同时另一种思路是转化为排列组合问题,即:需要走 m + n - 2 步,其中 m - 1向下,n - 1向右。也就是求解组合数:
C(m + n - 2, n - 1)
Solution
2D DP - O(mn) space, O(mn) time - (0ms, 100% AC)
C++ Ref: https://leetcode.com/problems/unique-paths/discuss/22981/My-AC-solution-using-formula
Reference
https://leetcode.com/problems/unique-paths/discuss/22981/My-AC-solution-using-formula
Last updated
Was this helpful?