LeetCode Combination Sum II
Combination Sum II
Original question
In an array (with repeated values), search for combinations of specific values.
Note:
All numbers in a positive number combination must be in ascending order. The numbers in the original array can only appear once, but cannot have repeated combinations.
Example:
Input: candidates = [10, 1, 2, 7, 6, 1, 5], target = 8
Output: [1, 1, 6], [1, 2, 5], [1, 7], [2, 6]
Solutions
This question is very similar to Combination Sum. The main difference is that elements in Combination Sum are not repeated, and each element can be used for an infinite number of times. The elements in this question are repeated, each element can be used only once. The initial idea was to add an element without considering the current element, and store the result in a set to prevent repeated combinations, but the result times out. Manually remove all elements that are equal to the current element.
AC Source Code
class Solution(object): def combinationSum2(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ if not candidates: return [] candidates.sort() result = [] self.combination(candidates, target, [], result) return result def combination(self, candidates, target, current, result): s = sum(current) if current else 0 if s > target: return elif s == target: result.append(current) return else: i = 0 while i < len(candidates): self.combination(candidates[i + 1:], target, current + [candidates[i]], result) # ignore repeating elements while i + 1 < len(candidates) and candidates[i] == candidates[i + 1]: i += 1 i += 1if __name__ == "__main__": assert Solution().combinationSum2([10, 1, 2, 7, 6, 1, 5], 8) == [[1, 1, 6], [1, 2, 5], [1, 7], [2, 6]]
Please check out my Github for relevant source code.