LeetCode Combination Sum
Combination Sum for solving LeetCode Problems
Original question
Find all combinations of sums and specific values in a set (no repeated numbers.
Note:
All numbers in a positive number combination must follow the order from small to large. The numbers in the original set can be repeated multiple times. A duplicate combination cannot exist, however, the input parameter type is list.
Example:
Input: candidates = [2, 3, 6, 7], target = 7
Output: [2, 2, 3], [7]
Solutions
The backtracking method is used. Since the numbers in the combination are sorted in order, we first sort the numbers in the set. Put the numbers in the combination in sequence, because all numbers are positive. If the current and has exceeded the target value, give up. If the sum is the target value, add the result set. If the sum is smaller than the target value, then add more elements. Duplicate combinations are not allowed in the result set. Therefore, only the current and subsequent elements are added when an element is added.
AC Source Code
class Solution(object): def combinationSum(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: for i, v in enumerate(candidates): self.combination(candidates[i:], target, current + [v], result)if __name__ == "__main__": assert Solution().combinationSum([2, 3, 6, 7], 7) == [[2, 2, 3], [7]]
Please check out my Github for relevant source code.