What is recursion & backtracking in Python?



In Python, recursion is a programming technique where a function calls itself to solve a problem. Backtracking means trying different options one by one and going back if one option doesn't work. It helps in solving problems step by step, like puzzles or finding the right path.

How Recursion and Backtracking Work Together

Imagine navigating a maze. We are trying a path, and if it hits a dead-end, we go back and try another. That's backtracking. The steps of trying and going back are done using recursive function calls. Backtracking frequently uses recursion to explore different possibilities

  • Go forward with a possible option.
  • If it doesn't work, backtrack and try the next.
  • This process is done using recursion, checking all possible combinations or paths.

The following is the diagrammatic representation of recursion & backtracking in Python.


Fibonacci Series

The Fibonacci series is a sequence where each number is the sum of the two previous ones. It starts with 0 and 1. Using recursion, we can calculate the nth Fibonacci number by calling the function to get (n-1) and (n-2), and then adding them.

Example

To calculate fibonacci(6), Python computes fibonacci(5) and fibonacci(4), and so on. This continues until it hits the base case (0 or 1), and then all results are added back together to get the final answer.

def fibonacci(n):
    if n == 0:
        return 0
    if n == 1:
        return 1
    return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(6))  

Following is the output of the above code ?

8

Sum of Natural Numbers

Let's calculate the sum of the first n natural numbers using recursion. At every step, we have to add the current number n to the sum of numbers before it, i.e., n-1.

Example

In the following example, the function keeps reducing n until it reaches 1 (base case). Then it adds 5 + 4 + 3 + 2 + 1 to give 15.

def sum_natural(n):
    if n == 1:
        return 1
    return n + sum_natural(n - 1)
print(sum_natural(5))  

Following is the output of the above code ?

15

Finding All Subsets of a Set

In this method, backtracking is used to find out all subsets (combinations) of a list. At each step, we choose to include or exclude the current item and proceed recursively.

Example

In this example, we want to find all possible combinations (or subsets) of a list. Using backtracking, we try every option, including a number or skipping it, and move forward step by step. If we reach the end, we print the current group. Then we go back (backtrack) and try another combination.

def find_subsets(nums, path=[], index=0):
    if index == len(nums):
        print(path)
        return
    # Try including the number
    find_subsets(nums, path + [nums[index]], index + 1)
    # Try excluding the number (backtrack)
    find_subsets(nums, path, index + 1)

find_subsets([1, 2])

Following is the output of the above code ?

[1, 2]
[1]
[2]
[]

Key Differences Between Recursion and Backtracking

The following are some of the key differences between recursion and backtracking.

Feature Recursion Backtracking
Definition Function calling itself Recursive approach to find valid solutions
Purpose Solve problems by breaking down Explore all possible options and the correct path
Used for Math problems, Tree/Graph traversal Puzzle solving, Combinations, Constraints
Key Concept Divide and conquer Try and fail, then undo (go back)
Updated on: 2025-04-22T19:10:15+05:30

887 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements