leetcode-39-Combination Sum

“””
39. Combination Sum
Description
HintsSubmissionsDiscussSolution
Given a set of candidate numbers (C) (without duplicates) and a target number (T),
find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:
[
[7],
[2, 2, 3]
]

"""
import copy


class Solution:
    def recursive(self,candidates,target_cur,nums_in,numlist_cur):
        """
        分为  每次从set里边循环所有数,已有值减去所有数,新值作为已有值,继续处理。遇到0 返回保存,负数去掉
        :param candidates:
        :param target:
        :return:
        """
        # numlist_cur_in=numlist_cur
        outlist=[]
        for index,num in enumerate(candidates):
            target_cur_new=target_cur-num
            if target_cur_new==0:
                numlist_cur.append(nums_in+[num])
            elif target_cur_new>0:
                self.recursive(candidates[index:],target_cur_new,nums_in+[num],numlist_cur)
            else:
                pass



    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        numlist_cur=[]

        out=self.recursive(candidates,target,[],numlist_cur)
        return numlist_cur
        # print(out)
        # print(numlist_cur)
class Solution_:
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        res = []
        self.rec(candidates, target, [], res)
        return res


    def rec(self, candidates, target, path, res):
        if target < 0:
            return
        if target == 0:
            res.append(path)
            return
        for i in range(len(candidates)):
            self.rec(candidates[i:], target - candidates[i], path + [candidates[i]], res)
if __name__=='__main__':
    st=Solution()
    nums=[2, 3, 6, 7]
    target=6
    out=st.combinationSum(nums,target)
    print(out)
    原文作者:龙仔
    原文地址: https://segmentfault.com/a/1190000013357234
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞