美文网首页
leetcode刷题之回溯

leetcode刷题之回溯

作者: sk邵楷 | 来源:发表于2022-11-27 22:40 被阅读0次

leetcode刷题,使用python

1, 组合总和 —— 0039 回溯 深度搜索

给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。

candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。

对于给定的输入,保证和为 target 的不同组合数少于 150 个。
示例 1:
输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
解释:
2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
7 也是一个候选, 7 = 7 。
仅有这两种组合。

from typing import  List

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        def dfs(candidates, begin, size, path, res, target):
            if target<0:
                return
            if target == 0:
                res.append(path)
                return

            for index in range(begin, size):
                dfs(candidates, index, size, path+[candidates[index]], res, target-candidates[index])

        size = len(candidates)
        if size == 0:
            return []
        path = []
        res = []
        dfs(candidates, 0, size, path, res, target)
        return res

S = Solution()
candidates = [2,3,6,7]
target = 7
print(S.combinationSum(candidates, target))

2, 组合总和 II —— 0040 回溯 深度搜索

给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用 一次 。
注意:解集不能包含重复的组合。
示例 1:
输入: candidates = [10,1,2,7,6,1,5], target = 8,
输出:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]

SumII.PNG
from typing import  List

class Solution:
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        #将数组进行升序排序
        candidates.sort()
        #结果列表
        ans = []
        #可能组合
        tmp = []

        def back_dfs(idx, total):
            if total == target:
                ans.append(tmp[::])
                return

            if total > target:
                return

            for i in range(idx, len(candidates)):
                #限制同一层不能选中值相同的元素
                #若有相同的元素, 优先选择靠前面的
                if i >= idx+1 and candidates[i-1] == candidates[i]:
                    continue

                total += candidates[i]
                tmp.append(candidates[i])
                #和39题不同, 这里直接进入递归下一层
                #从当前索引的下一位开始选取, 避免重复选择同个索引的元素
                back_dfs(i+1, total)

                #回溯
                tmp.pop()
                total -= candidates[i]

        total = 0
        back_dfs(0, total)
        return ans



S = Solution()
candidates = [10,1,2,7,6,1,5]
target = 8
print(S.combinationSum2(candidates, target))

相关文章

网友评论

      本文标题:leetcode刷题之回溯

      本文链接:https://www.haomeiwen.com/subject/djchfdtx.html