Leetcode 62. Unique Paths

https://leetcode.com/problems/unique-paths/

Medium

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

  • 动归。 dp[i][j]代表[i,j]的unique path,dp[i][j] = dp[i - 1][j] + dp[i][j - 1],dp[0, 0] = 1。
  • 第一种解法最简单直接。
  • 分析第一种解法代码发现,实际上只需要保存previous row和current row结果,由此得出第二种解法。
  • 再分析第二种解法代码发现,previous[j]实际上就是更新前的current[j],由此只需要保存current row结果就行。
  • https://leetcode.com/problems/unique-paths/discuss/22954/C%2B%2B-DP
 1 class Solution:
 2     def uniquePaths1(self, m: int, n: int) -> int:
 3         dp = [ [ 1 for x in range(n) ] for x in range(m) ]
 4         
 5         for i in range(1, m):
 6             for j in range(1, n):
 7                 dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
 8         
 9         return dp[m - 1][n - 1]        
10 
11     def uniquePaths2(self, m: int, n: int) -> int:
12         previous, current = [1] * n, [1] * n
13         
14         for i in range(1, m):
15             for j in range(1, n):
16                 current[j] = previous[j] + current[j - 1]
17             
18             current, previous = previous, current
19         
20         # note : previous not current
21         return previous[n - 1]
22     
23     def uniquePaths(self, m: int, n: int) -> int:
24         current = [1] * n
25         
26         for i in range(1, m):
27             for j in range(1, n):
28                 current[j] += current[j - 1]
29         
30         return current[n - 1]
View Python Code

 

posted on 2019-09-14 18:07  浩然119  阅读(107)  评论(0编辑  收藏  举报