代码改变世界

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

2018-07-19 05:56  Johnson_强生仔仔  阅读(243)  评论(0编辑  收藏  举报

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:

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)

 1 class Solution:
 2     def uniquePaths(self, m, n):
 3         if m == 0 or n == 0: return 0        
 4         ans = [[1]*n for _ in range(m)]
 5         for i in range(1, m):
 6             for j in range(1, n):
 7                 ans[i][j] = ans[i-1][j] + ans[i][j-1]
 8         return ans[-1][-1] 
 9         # or return ans[m-1][n-1]

 

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

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

 

4. Test cases

1) edge cases

2) 7, 3