Leetcode 40. 组合总和 II(回溯) —— python

1. 题目描述

给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用一次。
说明:

所有数字(包括目标数)都是正整数。
解集不能包含重复的组合。

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

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

2. 解题思路

(1)直接运用回溯法,穷举每个子集,将和为target的子集留下。
emmmmm跑了下代码答案是对的,但是 oj 运行超出时间限制。。。

超出时间限制的原因:当sum>target时,不应再往下继续遍历,浪费了很多时间。

代码实现:

class Solution:
    def combinationSum2(self, candidates, target: int):
        self.subSet = []
        self.res = []
        sortedCandidates = sorted(candidates)
        self.search(sortedCandidates,0,[])
        for sub in self.subSet:
            if(sum(sub) == target and sub not in self.res):
                self.res.append(sub)
        return self.res

    def search(self,nums, index, temp):
        if(index == len(nums) ):
            self.subSet.append(temp)
            return
        self.search(nums,index+1, temp+[nums[index]])
        self.search(nums, index + 1, temp)

(2)下午尝试另外一种方法
解题思路与组合总和题https://blog.csdn.net/u013075024/article/details/96140841类似,不同的是,这题要求每个位置上的元素只能出现一次,不能重复利用。所以,与组合总和题相比,改动了一行代码。
改动如下
Leetcode 39. 组合总和:
在这里插入图片描述
Leetcode 40. 组合总和 II
在这里插入图片描述
解法二:
代码实现:

class Solution:
    def combinationSum2(self, candidates, target):
        candidates.sort()
        self.res = []
        self.DFS(candidates, target, 0, [])
        return self.res

    def DFS(self, candidates, target, start, temp):
        if target == 0 and (temp not in self.res):
            return self.res.append(temp)

        for i in range(start, len(candidates)):
            if candidates[i] > target:
                return
               # 从candidates中遍历的当前元素的下一个元素开始,继续遍历
            self.DFS(candidates[i+1:], target - candidates[i], 0, temp + [candidates[i]])
发布了77 篇原创文章 · 获赞 9 · 访问量 6749

猜你喜欢

转载自blog.csdn.net/u013075024/article/details/96117080
今日推荐