问题:
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
对此有何解释?堆栈溢出某种?但是,它不会抛出任何异常.有没有办法克服这个递归调用?