0062. Unique Paths - chasel2361/leetcode GitHub Wiki

***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?
Note: m and n will be at most 100.

7 x 3 grid

Above is a 7 x 3 grid. How many possible unique paths are there?

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

因為這題有限制機器人只能往右或下走,所以可以發現走到每一個的方法,會是走到上方格與左方格的方法數總和,其中最左邊的 column 以及最上方的 row 每一個都只有一種走法,如此一來我們可以建立一個矩陣,每個格子的裡面儲存走到這個可能的方法數,就可以解決這個問題了。

一開始我的寫法是先建立一個最左邊以及最上方都為 1 的矩陣,再把其他格依序相加,最後回傳右下角的數字就可以了

class Solution:
    def uniquePaths(self, m: int, n: int) -> int:
        grid = [1 for _ in range(m)](/chasel2361/leetcode/wiki/1-for-_-in-range(m))
        grid.extend([[1] + [0 for _ in range(m - 1)] for _ in range(n - 1)])
            
        for i in range(1, n):
            for j in range(1, m):
                grid[i][j] = grid[i-1][j] + grid[i][j-1]
                    
        return grid[-1][-1]

但看了其他人的解法之後,發現只要建立全為 1 的矩陣也沒關係,因為原本我設為 0 的格子在計算的時候也會被洗掉XD,全部都設為 1 的話會方便很多,最後就會像這樣

class Solution:
    def uniquePaths(self, m: int, n: int) -> int:
        grid = [[1 for _ in range(m)] for __ in range(n)]
            
        for i in range(1, n):
            for j in range(1, m):
                grid[i][j] = grid[i-1][j] + grid[i][j-1]
                    
        return grid[-1][-1]

不過這樣的寫法僅限於格子數不多的狀況,時間跟空間複雜度是O(N**2)

如果格子很多的話還是要回到排列組合解

from math import factorial
class Solution:
    def uniquePaths(self, m: int, n: int) -> int:
        return factorial(m + n -2)//(factorial(m-1) * factorial(n-1))