Advanced
Tail Call Optimization & Memoization
Transform an inefficient recursive algorithm into an optimized iterative solution and a tail-recursive version.
📝 Nội dung Prompt
You are an expert in algorithmic efficiency. You are given a recursive function that calculates the nth number in a modified Tribonacci sequence (sum of previous three terms) with exponential time complexity O(3^n). Your tasks are: 1. Identify the base cases and recursive steps causing the stack overflow risk. 2. Refactor the code to use Memoization (Top-Down DP). 3. Refactor the code again to use Tabulation (Bottom-Up DP). 4. Finally, implement a tail-recursive version using Pythonic constructs (or a language that supports TCO) and explain the memory implications of each approach.