Combinations in C++

Generating all possible combinations of k numbers from a range 1 to n is a classic problem that can be solved efficiently using backtracking. For example, if n = 4 and k = 2, the combinations would be [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]].

In Python, we can implement this using recursion with backtracking to explore all possible combinations systematically.

Using Recursive Backtracking

The backtracking approach builds combinations incrementally and backtracks when a complete combination is found ?

def combine(n, k):
    result = []
    
    def backtrack(start, current_combination):
        # Base case: if we have k numbers, add to result
        if len(current_combination) == k:
            result.append(current_combination[:])  # Make a copy
            return
        
        # Try all numbers from start to n
        for i in range(start, n + 1):
            current_combination.append(i)
            backtrack(i + 1, current_combination)  # Move to next number
            current_combination.pop()  # Backtrack
    
    backtrack(1, [])
    return result

# Example usage
n, k = 4, 2
combinations = combine(n, k)
print(f"Combinations of {k} numbers from 1 to {n}:")
for combo in combinations:
    print(combo)
Combinations of 2 numbers from 1 to 4:
[1, 2]
[1, 3]
[1, 4]
[2, 3]
[2, 4]
[3, 4]

Using itertools.combinations

Python's itertools module provides a built-in function for generating combinations ?

import itertools

def get_combinations(n, k):
    numbers = range(1, n + 1)
    return list(itertools.combinations(numbers, k))

# Example usage
n, k = 5, 3
combinations = get_combinations(n, k)
print(f"Combinations of {k} numbers from 1 to {n}:")
for combo in combinations:
    print(list(combo))
Combinations of 3 numbers from 1 to 5:
[1, 2, 3]
[1, 2, 4]
[1, 2, 5]
[1, 3, 4]
[1, 3, 5]
[1, 4, 5]
[2, 3, 4]
[2, 3, 5]
[2, 4, 5]
[3, 4, 5]

How the Backtracking Algorithm Works

The recursive backtracking follows these steps:

  1. Base Case: If current combination has k elements, add it to results
  2. Recursive Case: Try each number from current start position to n
  3. Backtrack: Remove the last added number to try the next possibility
Backtracking Tree (n=4, k=2) [] [1] [2] [3] [4] [1,2] [1,3] [1,4] [2,3] [2,4] [3,4] Legend: Start Partial Complete

Comparison

Method Time Complexity Space Complexity Best For
Recursive Backtracking O(C(n,k)) O(k) Learning algorithm concepts
itertools.combinations O(C(n,k)) O(k) Production code, efficiency

Conclusion

Use itertools.combinations for production code as it's optimized and concise. The recursive backtracking approach is excellent for understanding the algorithm and can be customized for specific requirements.

Updated on: 2026-03-25T07:47:49+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements