栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

剑指 Offer II 082. 含有重复元素集合的组合

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

剑指 Offer II 082. 含有重复元素集合的组合

题目链接

力扣

题目描述

给定一个可能有重复数字的整数数组 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]
]
 

提示:

1 <= candidates.length <= 100
1 <= candidates[i] <= 50
1 <= target <= 30

解题思路

回溯法:

使用“不跳跃选取一样的元素”的方式避免得到重复的结果。
e.g. [a,a,a,a]这样的连续元素,只有连续选取前三个a,a,a才可以得到三个a的子

代码 Python
class Solution:
    def combinationSum2(self, candidates: list[int], target: int) -> list[list[int]]:
        def backTracking(cur_sum: int, index: int) -> None:
            if cur_sum == target:
                ans.append(path[:])
            else:
                for i in range(index, len(candidates)):
                    if i > index and candidates[i] == candidates[i - 1]:
                        continue
                    if cur_sum + candidates[i] > target:
                        break
                    else:
                        path.append(candidates[i])
                        backTracking(cur_sum + candidates[i], i + 1)
                        path.pop()

        ans, path = [], []
        candidates.sort()
        backTracking(0, 0)
        return ans

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1014256.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号