Problem
Given a collection of candidate numbers (candidates
) and a target number (target
), find all unique combinations in candidates
where the candidate numbers sums to target
.
Each number in candidates
may only be used once in the combination.
Note:
-
All numbers (including
target
) will be positive integers. -
The solution set must not contain duplicate combinations.
Example 1:
1 |
|
Example 2:
1 |
|
Explanation
-
We can use backtracking to solve this problem. The base case is
target = 0
. To improve performance, we can sort thecandidates
array first, if we encounter a number is greater than thetarget
, then we can break out the loop because we know the numbers after this current number are also greater than thetarget
. -
We cannot have duplicate elements, so we can check the element with current index
i
and its previous element, in other words,candidates[i]
andcandidates[i-1]
. If they are equal, then we ignore it andcontinue
iterate to the next element. Besides this condition, we also need to check current indexi
and the recursion’s starting indexstart
, if they are not equal andcandidates[i] == candidates[i-1]
, then we ignore this current index and continue the next iterating number. For example:1
2
3candidates = [2, 2', 3] 2 -> 3 (we want this because index of 2 is start index && 2’ == 2) 2’ -> 3 (we don’t want this because index of 2' > start index 1 && 2’ == 2)
Solution
1 |
|