leetcode:62ユニークなパス

タイトル

ロボットの左上隅に位置する  M  X  N  (下図の「開始」マーク)の格子。

ロボットは、任意の時点でダウンまたは右に移動することができます。ロボットは、(下図の「完了」マーク)グリッドの右下隅に到達しようとしています。

どのように多くの可能なユニークなパスがありますか?


上記は、7×3のグリッドです。どのように多くの可能なユニークなパスがありますか?

注: M  と  Nは  、ほとんど100であろう。

例1:

入力: M = 3、n = 2の
 出力: 3
 説明: 
左上から、右下に到達するための3つの合計があります:
1.右- >右- >ダウン
2.右- >ダウン- >右
3.ダウン- >右- >右

例2:

入力: M = 7、n = 3の
 出力: 28

思考

順列が問題です。

    def uniquePaths(self, m: int, n: int) -> int:
        total = m+n-2
        ans = 1
        for i in range(n-1):
            ans = ans * (total-i)
        for i in range(n-1):
            ans = ans//(i+1)
        return ans
        

アイデア2

再帰、経路数m行n列+ M =行の行数(N-1)、(M-1)列ライン数の行n列

import collections
def uniquePaths(self, m: int, n: int) -> int:
    paths = collections.defaultdict(lambda:1)
        for i in range(2,m+1):
            for j in range(2,n+1):
                paths[str(i)+","+str(j)] = paths[str(i-1)+","+str(j)] + paths[str(i)+","+str(j-1)]
        return paths[str(m)+","+str(n)]

 

公開された45元の記事 ウォンの賞賛1 ビュー3366

おすすめ

転載: blog.csdn.net/qq_22498427/article/details/104549335