递归2:设置value_a和mask_b两个数值,一个是记录值,一个是记录标志其是否有值。可以减少递归的运算阶
目的:计算斐波那契数列
F(0)=0,F(1)=1, F(n)=F(n-1)+F(n-2)(n>=2,n∈N*)
value_a = [
0
for i
in
range(
100000)]
mask_b = [
0]*
100000
def
function(
x):
if x==
0:
value_a[
0] =
0
mask_b[
0] =
1
return
0
elif x==
1:
value_a[
1] =
1
mask_b[
1] =
1
return
1
else:
x_1 =
0
x_2 =
0
if mask_b[x-
1] ==
1:
x_1 = value_a[x-
1]
else:
x_1 = function(x-
1)
value_a[x-
1] = x_1
mask_b[x-
1] =
1
x_2 = value_a[x-
2]
# if mask_b[x-2] == 1:
# x_2 = value_a[x-2]
# else:
# x_2 = function(x-2)
# value_a[x-2] = x_2
# mask_b[x-2] = 1
return x_1 + value_a[x-
2]
print function(
500)