Intermediate·Concept·2 min read

Recursion and backtracking in Python

Practice this question

Problems to practice

  • Fibonacci
  • Factorial
  • Permutations
  • Subsets
  • Combination Sum
  • N-Queens
  • Sudoku

Example: subset generation

Python
def subsets(nums):
    result = []

    def backtrack(start, path):
        result.append(path.copy())
        for i in range(start, len(nums)):
            path.append(nums[i])
            backtrack(i + 1, path)
            path.pop()

    backtrack(0, [])
    return result

Interview guidance

Backtracking tries a branch and then undoes it to continue exploring other cases.


Adapted from 18_DSA_PYTHON.md · “6. Recursion and backtracking in Python”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.