python网格统计_Python:当网格大小太大时,递归调用计数行走网格的方式会产生错误的答案...

问题:

Imagine you start at the corner of an X by Y grid. You can only move in two directions: right and down. How many possible paths are there for you to go from (0,0) to (X,Y)

我有两种方法,第一种是使用通过memoization增强的递归算法,第二种是使用二项式计数策略

递归方式

def gridMovingCount(x,y,cache):

if x == 0 or y == 0:

return 1

elif str(x)+":"+str(y) in cache:

return cache[str(x)+":"+str(y)]

else:

cache[str(x)+":"+str(y)] = gridMovingCount(x-1,cache) + gridMovingCount(x,y-1,cache)

return cache[str(x)+":"+str(y)]

二项式计数

def gridMovingCountByBinomial(x,y):

return int(math.factorial(x + y) / (math.factorial(x) * math.factorial(y)))

当x和y相对较小时,这两种方式给出相同的答案

#the same result

print(gridMovingCount(20,20,cache)) #137846528820

print(gridMovingCountByBinomial(20,20)) #137846528820

当x和y很大时

# gave different result

print(gridMovingCount(50,50,cache)) #100891344545564193334812497256

print(gridMovingCountByBinomial(50,50)) #100891344545564202071714955264

对此有何解释?堆栈溢出某种?但是,它不会抛出任何异常.有没有办法克服这个递归调用?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值