我用Python编写了一个算法,用于计算使用不同硬币面额获取一定金额的方法数:
@measure
def countChange(n, coin_list):
maxIndex = len(coin_list)
def count(n, current_index):
if n>0 and maxIndex>current_index:
c = 0
current = coin_list[current_index]
max_coeff = int(n/current)
for coeff in range(max_coeff+1):
c+=count(n-coeff*current, current_index+1)
elif n==0: return 1
else: return 0
return c
return count(n, 0)
我的算法使用一个索引来获取硬币面额,正如你所看到的,我的索引在每个堆栈框架中都是递增的。我意识到这个算法也可以这样写:
@measure
def countChange2(n, coin_list):
maxIndex = len(coin_list)
def count(n, current_index):
if n>0 and 0<=current_index:
c = 0
current = coin_list[current_index]
max_coeff = int(n/current)
for coeff in range(max_coeff+1):
c+=count(n-coeff*current, current_index-1)
elif n==0: return 1
else: return 0
return c
return count(n, maxIndex-1)
这一次,每当我进入一个堆栈帧时,索引都会减少。我比较了这些函数的执行时间,发现它们之间有着非常显著的差异:
print(countChange(30, range(1, 31)))
print(countChange2(30, range(1, 31)))
>> Call to countChange took 0.9956174254208345 secods.
>> Call to countChange2 took 0.037631815734429974 secods.
如果我甚至不缓存结果,为什么算法的执行时间会有很大差异?为什么索引的递增顺序会影响执行时间?
countChange
中按降序对列表进行排序来获得最小数量。coin_list.sort(reverse=True)
。 - Sean Fujiwara