Combination Sum in Python

The combination sum problem involves finding all unique combinations in a given array where the numbers sum to a target value. Numbers can be reused unlimited times. For example, with candidates [2,3,6,7] and target 7, the solutions are [[7], [2,2,3]].

Recursive Approach

We'll use a recursive backtracking approach that explores all possible combinations ?

class Solution:
    def combinationSum(self, candidates, target):
        result = []
        self.solve(candidates, target, 0, [], result)
        return result
    
    def solve(self, candidates, target, start, current, result):
        if target == 0:
            result.append(current[:])  # Add copy of current combination
            return
        
        if target < 0:
            return
        
        for i in range(start, len(candidates)):
            current.append(candidates[i])
            # Use same index 'i' to allow reuse of same number
            self.solve(candidates, target - candidates[i], i, current, result)
            current.pop()  # Backtrack

# Test the solution
solution = Solution()
candidates = [2, 3, 6, 7]
target = 7
print(solution.combinationSum(candidates, target))
[[2, 2, 3], [7]]

How the Algorithm Works

The recursive function explores combinations by ?

  • Base cases: If target becomes 0, we found a valid combination. If target becomes negative, the path is invalid.
  • Exploration: For each candidate starting from the current index, add it to the combination and recursively search.
  • Backtracking: Remove the last added element to try other possibilities.
  • Reuse allowed: We pass the same index i in recursion to allow reusing the same number.

Example with Larger Target

solution = Solution()
candidates = [2, 3, 6, 7, 8]
target = 10

result = solution.combinationSum(candidates, target)
print("Candidates:", candidates)
print("Target:", target)
print("All combinations:")
for combo in result:
    print(combo, "sum =", sum(combo))
Candidates: [2, 3, 6, 7, 8]
Target: 10
All combinations:
[2, 2, 2, 2, 2] sum = 10
[2, 2, 3, 3] sum = 10
[2, 2, 6] sum = 10
[2, 8] sum = 10
[3, 7] sum = 10

Optimized Version

We can optimize by sorting candidates first to enable early termination ?

class OptimizedSolution:
    def combinationSum(self, candidates, target):
        candidates.sort()  # Sort for optimization
        result = []
        self.solve(candidates, target, 0, [], result)
        return result
    
    def solve(self, candidates, target, start, current, result):
        if target == 0:
            result.append(current[:])
            return
        
        for i in range(start, len(candidates)):
            if candidates[i] > target:
                break  # No point checking larger numbers
            
            current.append(candidates[i])
            self.solve(candidates, target - candidates[i], i, current, result)
            current.pop()

# Test optimized version
optimized = OptimizedSolution()
print(optimized.combinationSum([2, 3, 6, 7], 7))
[[2, 2, 3], [7]]

Conclusion

The combination sum problem is efficiently solved using recursive backtracking. The key insight is allowing number reuse by passing the same index in recursive calls. Sorting candidates first enables early termination for better performance.

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

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements