LeetCode Combination Sum

Source: Internet
Author: User

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.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.