为何斐波那契递归函数需调用自身而非直接返回(num-1)+(num-2)?
return (num - 1) + (num - 2) Fails vs. Recursive fibonacci Calls Great question—let’s break down exactly what’s happening here, because it gets to the heart of how recursion works for problems like the Fibonacci sequence.
First, let’s recall the definition of the Fibonacci sequence your function is trying to implement:
- The 0th term is 0, the 1st term is 1
- For any term
n >= 2, the value is the sum of the (n-1)th term and the (n-2)th term of the Fibonacci sequence
The Problem with Your Initial Code
Your first attempt used:
return (num - 1) + (num - 2)
This just calculates the arithmetic sum of two integers: num-1 and num-2. It doesn’t care about the Fibonacci values of those smaller numbers—it’s just adding raw numbers.
For example:
- If
num = 3, this returns2 + 1 = 3, but the actual 3rd Fibonacci term isfibonacci(2) + fibonacci(1) = 1 + 1 = 2 - If
num = 4, this returns3 + 2 = 5, but the correct 4th term isfibonacci(3) + fibonacci(2) = 2 + 1 = 3
You’re skipping the core logic of the Fibonacci sequence: each term depends on the results of the sequence for smaller inputs, not just the smaller inputs themselves.
Why the Recursive Fix Works
The corrected code uses:
return fibonacci(num - 1) + fibonacci(num - 2)
This does exactly what the Fibonacci definition requires:
- It calls
fibonacci(num-1)to get the (num-1)th term of the sequence - It calls
fibonacci(num-2)to get the (num-2)th term - It adds those two sequence values together to get the current term
Let’s walk through fibonacci(3) to see it in action:
fibonacci(3)checksnum >=2, so it callsfibonacci(2)+fibonacci(1)fibonacci(2)callsfibonacci(1)+fibonacci(0)→ returns1 + 0 = 1fibonacci(1)hits the base case (num <2) and returns1
- So
fibonacci(3) = 1 + 1 = 2—which is the correct Fibonacci value.
Key Takeaway
Recursion for problems like Fibonacci isn’t just about using smaller numbers—it’s about using the function itself to solve smaller versions of the same problem. Your initial code solved a different problem (adding two integers) instead of the actual Fibonacci sequence problem (summing two prior sequence results).
内容的提问来源于stack exchange,提问作者Pawlick




