【題目描述】 bash
一定要走m+n-2步,從裏面選任意m-1步向右便可,組合問題。app
import math
class Solution(object):
def uniquePaths(self, m, n):
""" :type m: int :type n: int :rtype: int """
re=math.factorial(m+n-2)/math.factorial(n-1)/math.factorial(m-1)
return re
複製代碼
效果: ui
【思路二:動態規劃】spa
二維動態規劃,狀態轉移方程是dp[i][j]=dp[i-1][j]+dp[i][j-1]code
class Solution(object):
def uniquePaths(self, m, n):
""" :type m: int :type n: int :rtype: int """
dp=[]
for i in range(n):
dp.append([0]*m)
for i in range(n):
dp[i][0]=1
dp[0]=[1]*m
for i in range(1,n):
for j in range(1,m):
dp[i][j]=dp[i-1][j]+dp[i][j-1]
return dp[n-1][m-1]
複製代碼
效果: cdn