您的位置:首页 > 其它

EularProject 15: 方格迷宫的路径数

2015-01-27 11:58 134 查看

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?

Answer:
137846528820
Completed on Tue, 27 Jan 2015, 03:57
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))


time : <1s

------------------

祝身体健康,万事如意

华电北风吹

天津大学计算机科学与技术学院

天津市卫津路92号

邮编: 300072

邮箱: 1194603539@qq.com
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: