打卡群刷题总结0826——组合总和

时间:2022-07-24
本文章向大家介绍打卡群刷题总结0826——组合总和,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

题目:39. 组合总和

链接:https://leetcode-cn.com/problems/combination-sum

给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 candidates 中的数字可以无限制重复被选取。 说明: 所有数字(包括 target)都是正整数。 解集不能包含重复的组合。 示例 1: 输入:candidates = [2,3,6,7], target = 7, 所求解集为: [ [7], [2,2,3] ] 提示: 1 <= candidates.length <= 30 1 <= candidates[i] <= 200 candidate 中的每个元素都是独一无二的。 1 <= target <= 500

解题:

1、DFS:为了避免元素重复,可以将数组排序,在递归时,记录遍历的开始位置。

代码:

class Solution(object):
    def dfs(self, nums, start, target, current):
        if len(nums) == 0:
            return 
        if target == 0:
            self.res.append(current)
        else:
            for i in range(start, len(nums)):
                num = nums[i]
                if num > target:
                    break
                current2 = copy.copy(current)
                current2.append(num)
                self.dfs(nums, i, target - num, current2)
            
    
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        candidates.sort()
        self.res = []
        self.dfs(candidates, 0, target, [])
        return self.res

PS:刷了打卡群的题,再刷另一道题,并且总结,确实耗费很多时间。如果时间不够,以后的更新会总结打卡群的题。

PPS:还是得日更呀,总结一下总是好的。