Recursion Flashcards
What use Recursion?
Allows solving complex problem with simple solution, reduces coding, and leads to efficient programs
What is the recursive definition of factorial?
factorial(n) = n * factorial(n-1) with factorial(0) = 1
what happens in the first call of factorial(4)?
Calls factorial(3)
How does is factorial(4) broken down further?
4 * factorial(3)
Expand factorial (4) to the next step
43(2* factorial(1))
How does the recursion continue after 2 * factorial (1)?
2*(1 * Factorial(0))
What is factorial (0)?
1.
What does factorial(1) resolve to?
1 × 1 = 1.
Simplify 4 × 3 × 2.
24
Final result of factorial(4)?
24
What is shown when tracing recursive factorial?
Each function call and its return path.
What is the role of the stack in recursion?
It stores the state of each function call until it resolves.
How does space usage grow during recursion?
Each recursive call adds a new frame to the stack.
What is the recursive formula for sum(n)?
sum(n) = n + sum(n-1), with sum(0) = 0.
How is sum implemented in Java?
Recursively adding n to sum(n-1) until n = 0.
What is the recursive formula for Fibonacci numbers?
fib(n) = fib(n-1) + fib(n-2), with fib(0)=0, fib(1)=1.
How does recursion flow for fib(4)?
Breaks into calls to fib(3) and fib(2) and so on.
How is Fibonacci implemented in Java?
Recursively, with base cases for 0 and 1.
What are two key features of a recursive method?
A base case and a reduction toward the base case.
How can recursion be used to print a message n times?
Print once, then call recursively with (n-1) times.
What is an example of solving a problem both iteratively and recursively?
Checking if a string is a palindrome.
How does the non-recursive palindrome check work?
Using a while loop comparing characters from ends.
What is a simple recursive palindrome check?
Compare first and last characters and recurse on substring.
How can you improve the recursive palindrome check?
Use helper methods to avoid creating new substrings.