Given a collection of candidate numbers candidates (which may contain duplicates) 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.
Output: [[1,1,6],[1,2,5],[1,7],[2,6]]
Explanation: 1+1+6=8, 1+2+5=8, 1+7=8, 2+6=8.
Output: [[1,2,2],[5]]
Sort the array first. The key difference from Combination Sum I is that each element can only be used once (recurse with i+1) and we must skip duplicates at the same tree level to avoid duplicate combinations.
- Sort candidates to bring duplicates adjacent and enable pruning.
- In the loop, skip if
i > start && candidates[i] == candidates[i-1]. - Recurse with
i+1(noti) since each element is used at most once. - Prune when
candidates[i] > remaining.
Complexity Analysis:
Time complexity: O(2^n) in the worst case since each element is either included or excluded.
Space complexity: O(n) for the recursion stack.