您当前的位置: 首页 >  Python

Better Bench

暂无认证

  • 1浏览

    0关注

    695博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

【Leetcode刷题Python】40. 组合总和 II

Better Bench 发布时间:2022-08-02 11:46:38 ,浏览量:1

1 题目

给定一个候选人编号的集合 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] ]

示例 2:

输入: candidates = [2,5,2,1,2], target = 5, 输出: [ [1,2,2], [5] ]

2 解析

我们主要需要解决的就是数组元素存在重复情况的问题,下面是解决的办法:

首先先将数组进行排序,这样重复的元素位置相邻,可以快速去重; 因为不允许组合重复(相同数字不同排序视为重复),所以递归每层不能存在重复的元素。 为了避免重复选择同个元素,进入下层递归时,选择下一个索引位置对应的元素。 这里用一个简单图示来加深理解,如下: 在这里插入图片描述

3 Python实现
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 candidates[i-1] == candidates[i] and i-1 >= idx:
                    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
关注
打赏
1665674626
查看更多评论
立即登录/注册

微信扫码登录

0.0412s