使用一次递归调用实现递归 [英] Implement recursion using one recursive call
本文介绍了使用一次递归调用实现递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定如下函数:f(n) = f(n-1) + f(n-3) + f(n-4)
Given a function as follow : f(n) = f(n-1) + f(n-3) + f(n-4)
f(0) = 1
f(1) = 2
f(2) = 3
f(3) = 4
我知道在一个函数内使用三个递归调用来实现它.但我只想在函数内部进行一次递归调用.怎么做?
I know to implement it using recursion with three recursive calls inside one function. But I want to do it with only one recursion call inside the function. How it can be done ?
要使用 3 个递归调用来实现,这是我的代码:
To implement using 3 recursive calls here is my code :
def recur(n):
if n == 0:
return 1
elif n == 1:
return 2
elif n == 2:
return 3
elif n == 3:
return 4
else:
return recur(n-1) + recur(n-3) + recur(n-4) #this breaks the rule because there are 3 calls to recur
推荐答案
您的尝试方向正确,但需要稍作改动:
Your attempt is in the right direction but it needs a slight change:
def main():
while True:
n = input("Enter number : ")
recur(1,2,3,4,1,int(n))
def recur(firstNum,secondNum,thirdNum,fourthNum,counter,n):
if counter==n:
print (firstNum)
return
elif counter < n:
recur (secondNum,thirdNum,fourthNum,firstNum+secondNum+fourthNum,counter+1,n)
这篇关于使用一次递归调用实现递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文