File size: 2,220 Bytes
8a2dcce | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | TOPIC: Recursion Overview
DEFINITION: Recursion is a programming technique where a function invokes itself to solve a problem by breaking it down into smaller instances of the same problem. This approach helps in solving complex problems that can be decomposed into simpler sub-problems, making it easier to understand and implement the solution. It's particularly useful for problems that have a recursive structure.
TIME_COMPLEXITY: The time complexity of recursion can vary depending on the problem, but in general, it's O(2^n) in the worst case for problems like tree traversals, O(n) for problems like array sum, and can be optimized to O(log n) for problems like binary search, due to the repeated function calls.
SPACE_COMPLEXITY: The space complexity of recursion is typically O(n), where n is the maximum depth of the recursion call stack, as each recursive call adds a new layer to the call stack.
USE_WHEN: Recursion is the right tool when dealing with problems that have a recursive structure, such as tree or graph traversals, or when the problem can be broken down into smaller sub-problems of the same type. It's particularly useful when the problem has a clear base case and a recursive case.
AVOID_WHEN: Recursion can be a poor choice when dealing with large problems or problems that require a high degree of efficiency, as the repeated function calls can lead to stack overflow errors, and in such cases, iterative solutions are often preferred.
EXAMPLE:
Consider a simple recursive function to calculate the sum of an array: [1, 2, 3, 4]
-> sum([1, 2, 3, 4]) = 1 + sum([2, 3, 4])
-> sum([2, 3, 4]) = 2 + sum([3, 4])
-> sum([3, 4]) = 3 + sum([4])
-> sum([4]) = 4 + sum([])
-> sum([]) = 0 (base case)
<- sum([4]) = 4
<- sum([3, 4]) = 7
<- sum([2, 3, 4]) = 9
<- sum([1, 2, 3, 4]) = 10
Checkmark: sum = 10
REAL_WORLD_ANALOGY: Recursion is similar to a set of Russian nesting dolls, where each doll contains a smaller version of itself, and the process of opening each doll to find the smaller one is similar to the recursive function calls.
SOURCE_NOTE: Concepts referenced from general knowledge of programming principles and data structures. |