EularProject 15: 方格迷宫的路径数

本文详细介绍了使用动态规划方法解决20×20网格中从左上角到右下角的不同路径数量的问题。通过记忆化递归实现高效的计算,并对比了直接使用组合数学公式的方法。代码实现简洁高效,展示了算法在实际问题解决中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值