[LeetCode] 62. Unique Paths_ Medium tag: Dynamic Programming

时间:2024-01-16 14:36:02

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?

[LeetCode] 62. Unique Paths_ Medium tag: Dynamic Programming
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:

Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right

Example 2:

Input: m = 7, n = 3
Output: 28

这个题目思路就是dynamic programming, A[i][j] = A[i-1][j] + A[i][j-1] , i, j >= 1.     T: O(m*n)  , S: O(n)   optimal(用滚动数组)

1. Constraints.

1) size [0*0] - [100*100]

2) edge case, m==0 or n ==0 => 0

2. Ideas

DP    T: O(m*n)   S; O(m*n)

3. Codes

1)  T: O(m*n)  , S: O(m*n)

 class Solution:
def uniquePaths(self, m, n):
if m == 0 or n == 0: return
ans = [[1]*n for _ in range(m)]
for i in range(1, m):
for j in range(1, n):
ans[i][j] = ans[i-1][j] + ans[i][j-1]
return ans[-1][-1]
# or return ans[m-1][n-1]

2) T: O(m*n)  , S: O(n)   滚动数组

 class Solution:
def uniquePaths(self, m, n):
if m == 0 or n == 0: return
ans = [[1] *n for _ in range(2)] # 模2
for i in range(1, m):
for j in range(1, n):
ans[i%2][j] = ans[i%2-1][j] + ans[i%2][j-1]
return ans[(m-1)%2][n-1]

4. Test cases

1) edge cases

2) 7, 3