Lattice paths
Problem 15
Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner.

How many such routes are there through a 20×20 grid?
dict={}
def func(i,j):
rest=dict.get(str(i)+'_'+str(j))
if rest!=None:
return rest
else:
if i==0 or j==0:
return 1
temp=func(i-1,j)+func(i,j-1)
dict[str(i)+'_'+str(j)]=temp
return temp
result=func(20,20)
print(result)
上面的代码用到了带记忆的自上向下的动态规划算法。鉴于题目的特殊性,可以发现用组合数公式可以直接求解。
import operator
from functools import reduce
def c(n,k):
return reduce(operator.mul,range(n - k + 1, n + 1)) //reduce(operator.mul, range(1, k +1))
def fac(n):
return reduce(operator.mul, range(1,n+1))
a,b=20,20
print(c(a+b,a))
------------------