Leetcode_39【组合总和】

时间:2019-12-20 10:42:54   收藏:0   阅读:76

文章目录:


题目:

给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的数字可以无限制重复被选取。

说明:

所有数字(包括 target)都是正整数。
解集不能包含重复的组合。 
示例 1:

输入: candidates = [2,3,6,7], target = 7,
所求解集为:
[
[7],
[2,2,3]
]
示例 2:

输入: candidates = [2,3,5], target = 8,
所求解集为:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]


脚本一:【用时:630ms】

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        list1 = []
        list3 = []
        ret = []
        for i in candidates:
            list1.append(list(range(i,i+1)))
            list2 = list1[:]
        def diedai(l1,l2,target):
            n1 = len(l1)
            for i in range(n1):
                for j in l2:
                    bb = l1[i] + j
                    if sum(bb) <= target:
                        bb.sort()
                        l1.append(bb)
        while list2:
            list3 = []
            for i in list2:
                if sum(i) == target:
                    if i not in ret:
                        ret.append(i)
                    list3.append(i)
                elif sum(i) < target:
                    list3.append(i)
            list2 = list3
            if list2:
                n2 = len(list2)
                diedai(list2,list1,target)
                del list2[0:n2]
            else:
                break
        return(ret)

脚本一逻辑:


 

脚本二:【用时:100ms】【转载】

class Solution(object):
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        def searchSum(candidates,target):
            res=[]
            for i in range(len(candidates)):
                num=candidates[i]
                if num<target:
                    #为了去重,从当前位置开始搜索解
                    l=searchSum(candidates[i:],target-num)
                    if l!=[]:
                        for ele in l:
                            ele.append(num)
                    res=res+l
                elif num==target:
                    res=res+[[num]]
            return res

        return searchSum(candidates,target)

脚本二逻辑:


 

shell处理分享:

原文:https://www.cnblogs.com/mailong/p/12070897.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!