0
点赞
收藏
分享

微信扫一扫

精简版win10系统,添加程序没有iis组件无法添加怎么办

【组合回溯递归】【树层去重used标记】Leetcode 40. 组合总和 II

---------------🎈🎈40. 组合总和 II 题目链接🎈🎈-------------------
在这里插入图片描述

解法 组合问题常用解法 + 树层去重

在这里插入图片描述

问题描述:(数组candidates)有重复元素,但还不能有重复的组合
操作:去重的是“同一树层上的使用过的元素”
核心:加入一个used数组,去重时结合:前后数字相同的判断 + used[i-1]未被使用的判断,若成立则continue当前for遍历

说明:

时间复杂度O(N)
空间复杂度O(N)

class Solution {
    List<List<Integer>> result = new ArrayList<>();
    List<Integer> temp = new ArrayList<>();

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        int[] used = new int[candidates.length]; // 初始化一个used数组 均为0, 表示都没有使用
        helper(candidates,target,0,0,used);
        return result;

    }
    public void helper(int[] candidates, int target, int startnum, int sum, int[] used){
        // 终止条件
        if(sum==target){ 
            result.add(new ArrayList<>(temp));
        }
        if(sum>target){
            return;
        }

        // 树层去重
        
        for(int i = startnum; i<candidates.length; i++){
            // 当前面的一个元素和现在的元素相同,且前面一个元素并未被使用的时候,跳过(因为所有可能都已经被前面的元素查找过了)
            if(i>0 && used[i-1]!=1 && candidates[i] == candidates[i-1]){  
                continue;
            }
            used[i] = 1; // 置为一:标志着第i个元素被使用
            sum+=candidates[i];
            temp.add(candidates[i]);
            helper(candidates,target,i+1,sum,used); // 递归
            temp.removeLast();
            sum-=candidates[i];
            used[i] = 0; // 回溯恢复

        }
    }
}      
举报

相关推荐

0 条评论