leetcode python 39. 组合总和(中等,数组,递归)

给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的数字可以无限制重复被选取。
说明:所有数字(包括 target)都是正整数。解集不能包含重复的组合。

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

思路:
1.target要一次一次不断的更新,因此需要递归
2.结果不要重复,防止出现【2,2,3】和【3,2,2】,所以要给数组排序,依次向后挑选。
3.挑选时只选择比过去挑过的大,因为数组没有重复值,所以不会出现重复的情况。

class Solution:
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        self.result=[]      #类函数的全局变量
        candidates=sorted(candidates)   #排序
        self.dummy(candidates,target,[],0)
        return self.result
        
    def dummy(self,candidates,target,s,corr):
        if target==0:
            self.result.append(s[:])
        if target<candidates[0]:
            return
        for i in candidates:     #因为i没有重复,依次向后走,所以递归的结果不会重复
            if i >target:
                return
            if i<corr:
                continue
            s.append(i)
            self.dummy(candidates,target-i,s,i)
            s.pop()
        #具体的递归过程要在纸上写写

执行用时: 100 ms, 在Combination Sum的Python3提交中击败了71.46% 的用户

猜你喜欢

转载自blog.csdn.net/weixin_42234472/article/details/84786452
今日推荐