AlgoMaster Logo

Combination Sum II

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Backtracking with Sorting and Skip Duplicates

Intuition:

The problem is to find all unique combinations of numbers that add up to a given target. Each number in the array can be used only once. For this, we can use a backtracking approach. First, we sort the array to make it easier to handle duplicates and to potentially stop early when the remaining candidates are all larger than the target left to achieve. By sorting, we also ensure that duplicates are adjacent, which allows us to easily skip over them.

Steps:

  1. Sort the Array: Sorting helps in quickly identifying and skipping duplicates.
  2. Use a helper function to recursively build possible combinations.
  3. If the target equals zero, add the current combination to the results.
  4. If the target goes below zero, exit this path as it cannot produce a valid result.
  5. Iterate through the candidates:
    • Skip duplicate elements by checking if the current element is the same as the previous one (to prevent duplicate combinations).
    • Make a recursive call to include the current element and reduce the target by its value.
    • Backtrack by removing the last added element from the current combination.

Code:

2. Backtracking Optimized with Early Exit

Intuition:

This approach is similar to Approach 1 but adds a further optimization to stop early in the loop. By stopping early once we encounter candidates larger than the current remaining target (after checking the first element due to sorted order), we avoid unnecessary recursive calls.

Steps:

  • The structure of the function remains largely the same as Approach 1.
  • The critical change is in the loop where we stop iterating over candidates as soon as we find one greater than the remaining target.

Code: