Recursion

Recursion Example

What is Recursion?

Recursion is a technique where a function calls itself to solve a smaller instance of the same problem.

It is typically used when:

  • The problem can be broken down into smaller subproblems.
  • Each decision reduces the input size until a base case is reached.

How to Identify Recursion?

A problem is recursive if:

  • We need to make decisions based on choices.
  • Each choice leads to a smaller input or simpler version of the problem.
  • There is a clear base case (a stopping condition) where recursion ends.
  • The subproblems can be combined to form the final solution.
๐Ÿ‘‰ Choices + Decisions = Recursion

Example: Subsequence / Substring Generation

Consider the string: const s = "abc";

Recursion is about making binary choices at each step: include or exclude each character from the original string. Exploring all such decision paths results in all possible subsequences.

Recursive Decision

For each character in the string, we recursively decide to:

  • Include the character.
  • Exclude the character.

Generating All Subsequences: Recursive Tree Approach

Outputabc
""โœ—โœ—โœ—
aโœ“โœ—โœ—
bโœ—โœ“โœ—
cโœ—โœ—โœ“
abโœ“โœ“โœ—
bcโœ—โœ“โœ“
acโœ“โœ—โœ“
abcโœ“โœ“โœ“

โœ” = character included
โœ— = character excluded

Recursion LeetCode Problems

Problem TitleDifficultyDescription
Generate ParenthesesMediumGenerate all combinations of well-formed parentheses given n pairs.
PermutationsMediumReturn all possible permutations of a list of distinct numbers.
Permutations IIMediumReturn all unique permutations of a list that may contain duplicates.
CombinationsMediumGenerate all possible combinations of k numbers from 1 to n.
SubsetsMediumReturn all possible subsets (the power set) of a list of numbers.
Subsets IIMediumReturn all possible subsets of numbers that may contain duplicates.
Combination SumMediumFind all unique combinations of candidates that sum to a target (reusing allowed).
Combination Sum IIMediumFind all unique combinations of candidates that sum to a target (no reuse).
Combination Sum IIIMediumFind all valid combinations of k numbers (1โ€“9) that sum to n.
Palindrome PartitioningMediumPartition a string into substrings such that every substring is a palindrome.
Restore IP AddressesMediumReturn all possible valid IP address combinations from a string of digits.
Binary WatchMediumReturn all possible times a binary watch could represent given turned-on LEDs.