【题目描述】
【思路一:数学方法】必定要走m+n-2步,从里面选任意m-1步向右即可,组合问题。
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
效果:
【思路二:动态规划】
二维动态规划,状态转移方程是dp[i][j]=dp[i-1][j]+dp[i][j-1]
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]
效果: