AlgoMaster Logo

Combination Sum

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Backtracking

Intuition:

The problem requires us to find all unique combinations of numbers that sum up to a target, allowing unlimited usage of each number. This is a classical combination problem suitable for backtracking, where we try all possibilities and backtrack once we exceed the target or if we've considered the entire list of candidates.

Steps:

  1. We will sort the input array to help in potential optimizations, although not necessary in this approach.
  2. Use a recursive backtracking function to explore each combination:
    • Include the current candidate in the path and recursively attempt to compute the remaining target.
    • If at any point, our current combination sums to the target, save it.
    • If the sum exceeds the target, backtrack.
  3. We avoid duplicates by ensuring each combination is built in non-decreasing order.

Code:

2. Backtracking with Pruning

Intuition:

In the previous approach, we performed unnecessary recursive calls even when these calls wouldn't have contributed to a valid combination. By sorting the array initially, we can prune these branches more aggressively and stop processing further once we encounter a candidate larger than the target or the remaining target during recursion.

Steps:

  1. Begin with sorting the candidates which can make pruning easier.
  2. While exploring candidates, terminate early if the current candidate exceeds the reduced target at any point, avoiding wasting computation on invalid paths.
  3. This slight change saves processing time and makes the solution more efficient.

Code: