Useful recursive functions
Recursion to find all possible permutations
n = int(input())
def backtrack(path, used):
# Base case: all n numbers are placed
if len(path) == n:
answer.append(path[:]) # Save a copy, not a reference!
return
for num in range(1, n + 1):
if not used[num]:
used[num] = True
path.append(num)
backtrack(path, used)
# Backtrack (undo choices)
path.pop()
used[num] = False
answer = []
used = [False] * (n + 1) # 1-indexed boolean array for numbers 1..n
backtrack([], used)
for perm in answer:
print(*perm)Recursion to find distinct permutation of a list(with repeated elements)
def backtrack(path, used, nums):
if len(path) == len(nums):
permutations.append(path[:])
return
for idx in range(len(nums)):
if used[idx]:
continue
# Skip duplicate elements at the same recursion level
if idx > 0 and nums[idx] == nums[idx - 1] and not used[idx - 1]:
continue
used[idx] = True
path.append(nums[idx]) # Append the value, not the index
backtrack(path, used, nums)
path.pop()
used[idx] = False
permutations = []
nums = [1, 1, 1, 2, 3, 4]
nums.sort() # Ensure equal elements are adjacent
used = [False] * len(nums)
backtrack([], used, nums)
for perm in permutations:
print(*perm)Recursive functions and time complexity
Summary: Efficient Stair Climbing & Recursive Execution
1. The Core Problem
To find the number of ways to climb stairs taking or steps at a time, the recursive formula is:
-
Base Cases: , .
-
The Inefficiency: Naive recursion recalculates the exact same branches repeatedly, leading to exponential time complexity (). For , it triggers over 126 million function calls.
2. How Python Executes Recursion (Left vs. Right)
-
Code Order Determines Children: Because
f(n-1)is written to the left of the+sign inf(n-1) + f(n-2), Python evaluates it first. Thus,n - 1becomes the left child andn - 2becomes the right child. -
Depth-First Traversal: Python evaluates expressions left-to-right. It dives all the way down the leftmost path first until it hits a base case before looking at any right-side branches.
Execution Tree Diagram ()
f(5) [Call #1]
/ \
[LEFT] f(4) f(3) [RIGHT - Calculated from scratch in Naive]
/ \
f(3) f(2)
/ \
f(2) f(1)
Step-by-Step Traversal Path:
-
Dives Leftmost: (Base Case = 2).
-
Backtracks & Evaluates Right Sibling: calls right child (Base Case = 1). Calculates .
-
Backtracks & Evaluates Right Sibling: calls right child (Base Case = 2). Calculates .
-
Reaches Top Right Sibling: finally calls right child .
3. The Solution: Memoization (Caching)
Memoization saves computed answers in a dictionary, reducing time complexity from exponential down to linear .
-
Left Branch Populates Cache: While diving down the left side (
n-1), Python computes and stores the answers for every value from up to in the dictionary. -
Right Branch Triggers Cache Hit: When Python backtracks to evaluate right-side calls (
n-2),nis already in the dictionary. -
Instant Lookup: Instead of recalculating a full recursive subtree, Python grabs the answer from memory in constant time.
4. Code Implementations
Method A: Explicit Memoization Dictionary
Python
def climb_stairs(n, memo=None):
if memo is None:
memo = {}
if n <= 2:
return n
# Check cache before doing any recursive calls
if n in memo:
return memo[n]
# Calculate, store in cache, then return
memo[n] = climb_stairs(n - 1, memo) + climb_stairs(n - 2, memo)
return memo[n]
Method B: Built-in Python Decorator
Python
from functools import cache
@cache
def climb_stairs(n):
if n <= 2:
return n
return climb_stairs(n - 1) + climb_stairs(n - 2)