资讯专栏INFORMATION COLUMN

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

XUI / 769人阅读

摘要:题目给定一个可能有重复数字的整数数组和一个目标数,找出中所有可以使数字和为的组合。中的每个数字在每个组合中只能使用一次,解集不能包含重复的组合。示例输入输出示例输入输出提示注意本题与主站题相同答案回溯法排序后去重

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

注意:本题与主站 40 题相同: https://leetcode-cn.com/problems/combination-sum-ii/

答案:

class Solution {    List<List<Integer>> lists;    public List<List<Integer>> combinationSum2(int[] candidates, int target) {        //回溯法,排序后去重        Arrays.sort(candidates);        lists = new ArrayList<>();        List<Integer> list = new ArrayList<>();        backTrace(list, candidates, target, 0);        return lists;    }    public void backTrace(List<Integer> list, int[] candidates, int target, int index){        if(target == 0){            lists.add(new ArrayList<>(list));            return;        }        if(index >= candidates.length) return;        if(target < 0 && candidates[index] > 0) return;        for(int i = index; i < candidates.length; i++){            list.add(candidates[i]);            backTrace(list, candidates, target - candidates[i], i + 1);            while (i < candidates.length - 1 && candidates[i] == candidates[i + 1]) {                i++;            }            list.remove(list.size() - 1);        }    }}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/123185.html

相关文章

发表评论

0条评论

最新活动
阅读需要支付1元查看
<