Combination Sum II

Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.

Each number in candidates may only be used once in the combination.

Note: The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8

Output: [ [1,1,6], [1,2,5], [1,7], [2,6] ]

Example 2:

Input: candidates = [2,5,2,1,2], target = 5

Output: [ [1,2,2], [5] ]

Constraints:

  • 1 <= candidates.length <= 100
  • 1 <= candidates[i] <= 50
  • 1 <= target <= 30

Solution

The logics for the template are:

  • start_index: the start index of the next potential candidate in candidates.
  • is_leaf: if remaining == 0 we have reached our target using elements in path.
  • get_edges: all candidates in candidates[start_index:].
  • is_valid: candidate[i] is valid if it does not exceed remaining and is not a duplicate.

We will follow the same steps as in Deduplication to validate and avoid a duplicate candidate.

Implementation

def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
    def dfs(start_index, path, remaining):
        if remaining == 0:
            ans.append(path[:])
        for i in range(start_index, len(candidates)):
            if remaining - candidates[i] < 0:   # avoid results exceeding target
                break
            elif i != start_index and candidates[i] == candidates[i-1]: # avoid duplicates
                continue
            path.append(candidates[i])
            dfs(i+1, path, remaining - candidates[i])
            path.pop()
    candidates.sort()
    ans = []
    dfs(0, [], target)
    return ans

Ready to land your dream job?

Unlock your dream job with a 2-minute evaluator for a personalized learning plan!

Start Evaluator
Discover Your Strengths and Weaknesses: Take Our 2-Minute Quiz to Tailor Your Study Plan:
Question 1 out of 10

A person thinks of a number between 1 and 1000. You may ask any number questions to them, provided that the question can be answered with either "yes" or "no".

What is the minimum number of questions you needed to ask so that you are guaranteed to know the number that the person is thinking?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!


Load More