Explore the core principles of recursion and backtracking with scenario-driven questions designed to deepen understanding of function calls, stack usage, base cases, and solution space exploration. Evaluate your grasp of recursive algorithms and essential backtracking strategies to improve your problem-solving skills in computer science.
Which of the following base cases correctly terminates a recursive function designed to calculate the factorial of a positive integer n?
Explanation: The correct base case for factorial is 'When n == 1, return 1' because factorial of 1 is defined as 1 and stops recursion. Returning 0 when n == 0 is incorrect, as factorial of 0 is 1. Returning 1 for n u003C 0 is invalid since factorial isn't defined for negative numbers. Returning n when n == 2 does not halt the recursion properly, as factorial for 2 should follow the same pattern as for other positive integers.
Given a backtracking algorithm for generating all possible subsets of the set {1, 2}, which of the following accurately represents the complete output?
Explanation: Backtracking generates all possible combinations including the empty set, so '[[], [1], [2], [1, 2]]' is correct. The option missing the empty set is incomplete. '[[], [1, 2], [2, 1]]' lists [2, 1], which is not a distinct subset but a permutation. '[[], [1], [1, 2]]' leaves out the subset [2], so it's also inaccurate.
What is a common cause for a stack overflow error when running recursive code to calculate Fibonacci numbers?
Explanation: A missing base case allows recursion to continue indefinitely, leading to stack overflow. Choosing the wrong return type may cause compile-time errors, but not stack overflow. Limiting recursion depth prevents the error rather than causing it. Passing parameters by reference impacts memory usage but does not inherently cause stack overflow.
If a function recurses to sum digits of an integer n (e.g., n = 1234), which sequence of calls happens for the initial input?
Explanation: Recursive digit-sum typically removes the last digit each step, so the function is called with 1234, then 123, 12, and 1. The other options skip digits or rearrange the order incorrectly, or attempt calls with non-sequential values. Only the first option shows correct decreasing order of calls by dividing by 10.
When solving a Sudoku puzzle with backtracking, what is the main reason for choosing to try all numbers from 1 to 9 in each empty cell?
Explanation: Backtracking in Sudoku tries all options to ensure every valid possibility is considered for each cell. Assuming only odd numbers are valid contradicts Sudoku rules. While efficient implementations prune branches, the method does not inherently minimize the number of calls. Cells do not have to be filled strictly sequentially; order can vary.