时间复杂度O(n2)
def uniquePaths(m, n):
"""
计算路径的个数
"""
memo = [[0 for j in range(n)] for i in range(m)]
for i in range(m):
for j in range(n):
if i == 0 and j == 0:
memo[i][j] = 1
elif j == 0:
memo[i][j] = memo[i - 1][j]
elif i == 0:
memo[i][j] = memo[i][j - 1]
else:
memo[i][j] = memo[i - 1][j] + memo[i][j - 1]
print(memo[m-1][n-1])
return memo[m - 1][n - 1]
时间复杂度O(n)
def uniquePaths_one(m, n):
"""
j表示列,j-1 表示左右方向比较,j表示上下方向比较
"""
memo = [0 for j in range(n)]
for i in range(m):
for j in range(n):
if i == 0 and j == 0:
memo[j] = 1
elif j == 0:
memo[j] = memo[j]
elif i == 0:
memo[j] = memo[j-1]
else:
memo[j] = memo[j] + memo[j - 1]
print(memo[n-1])
return memo[n - 1]
利用数学公式计算,组合问题
def uniquePaths_zuhe(m,n): ###m,n表示行列
total = m + n -2
sub = m- 1
ret = 1
for i in range(1,sub+1):
ret = int(ret * (total - sub + i) /i)
print(ret)
return ret