剑指offer 专项突破版 82、含有重复元素集合的组合

这篇博客探讨了解决组合问题的Java算法,特别是针对数组中有重复元素的情况。通过排序数组并使用递归策略,算法避免了重复组合的生成。关键在于,当决定不选择某个元素时,不再考虑与其相同的后续元素,从而确保结果的唯一性。这种方法提高了搜索效率,并且适用于目标和数组元素都可能包含重复值的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

思路
  • 首先要明白为什么会重复。以[2,2,2,3] 7 为例。因为2重复了三次,所以有可能选择答案的索引为[0,1,3]、[0,2,3]、[1,2,3]
  • 之所以会这样是因为可能我们选择了第0个、第1个元素;或者是选择了第0个元素,没选择第1个元素,又选择了第2个元素。对于元素不重复的数组,这样是没问题的。但是对于元素重复的数组,这样就会产生重复的答案
  • 所以解决办法为,当我们决定不选择某个元素时,在调用helper函数时,index应该传下一个和该索引元素不同的元素的索引
  • 回到我们的例子中,也就是说如果某一步我们决定不再选择2时,下一步的helper函数应该传入的索引为3,也就是元素3对应的索引
public class Solution {
    List<List<Integer>> result;
    int[] nums;
    int target;

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        result = new ArrayList<>();
        nums = candidates;
        this.target = target;

        //先排序 这样才能去重
        Arrays.sort(nums);
        helper(new ArrayList<>(), 0, 0);
        return result;
    }

    private void helper(List<Integer> combination, int index, int sum) {
        if (sum == target)
            result.add(new ArrayList<>(combination));
        else if (index < nums.length && sum < target) {
            // 不选择现在索引对应的数 那就跳过所有和当前索引相同的数
            int nextIndex = index + 1;                                               
            while (nextIndex < nums.length && nums[index] == nums[nextIndex]) 
                nextIndex++;    
            helper(combination, nextIndex, sum);

            //选择现在的索引对应的数 但是索引不增加
            combination.add(nums[index]);
            helper(combination, index + 1, sum + nums[index]);
            combination.remove(combination.size() - 1);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值