https://leetcode.com/problems/unique-paths/description/web
62. Unique Paths優化
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).spa
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).code
How many possible unique paths are there?blog
Above is a 7 x 3 grid. How many possible unique paths are there?ip
Note: m and n will be at most 100.leetcode
Example 1:get
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:it
Input: m = 7, n = 3
Output: 28
一個機器人位於m x n隔板的左上角(在圖中標記爲「起點」)。io
機器人在任意一點只能夠向下或者向右移動一步。機器人嘗試到達隔板的右下角(圖中標記爲「終點」)
有多少種可能的路徑?
注意:m和n最多爲100
狀態轉移方程:
dp[x][y] = dp[x - 1][y] + dp[x][y - 1]
初始令dp[0][0] = 1
Python代碼:
class Solution(object): def uniquePaths(self, m, n): """ :type m: int :type n: int :rtype: int """ dp = [[0] * n for x in range(m)] dp[0][0] = 1 for x in range(m): for y in range(n): if x + 1 < m: dp[x + 1][y] += dp[x][y] if y + 1 < n: dp[x][y + 1] += dp[x][y] return dp[m - 1][n - 1]
上述解法空間複雜度能夠優化至O(n):
class Solution(object): def uniquePaths(self, m, n): """ :type m: int :type n: int :rtype: int """ if m < n: m, n = n, m dp = [0] * n dp[0] = 1 for x in range(m): for y in range(n - 1): dp[y + 1] += dp[y] return dp[n - 1]
題目能夠轉化爲下面的問題:
求m - 1個白球,n - 1個黑球的排列方式
公式爲:
公式爲:C(m + n - 2, n - 1)
Python代碼:
class Solution(object): def uniquePaths(self, m, n): """ :type m: int :type n: int :rtype: int """ if m < n: m, n = n, m mul = lambda x, y: reduce(operator.mul, range(x, y), 1) return mul(m, m + n - 1) / mul(1, n)
參考:http://bookshadow.com/weblog/2015/10/11/leetcode-unique-paths/