leetcode40 组合数总和2

code

一开始是这样写的,但是发现有重复的现象,于是把数组排序了一下,在回溯过程中添加判断条件去重。

class Solution {
    
    

    List<List<Integer>> res = new ArrayList<>();
    boolean vis[];

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
    
    
        vis = new boolean[candidates.length];
        List<Integer> path = new ArrayList<>();
        helper(0, target, candidates, path);
        return res;
    }

    private void helper(int id, int target, int[] nums, List<Integer> path){
    
    
        if (id == nums.length) return;
        if (target == 0){
    
    
            res.add(new ArrayList<>(path));
            return;
        }


        helper(id + 1, target, nums, path);

        if (target >= nums[id] && !vis[id]){
    
    
            vis[id] = true;
            path.add(nums[id]);
            helper(id, target - nums[id], nums, path);
            vis[id] = false;
            path.remove(path.size() - 1);
        }

    }
}

AC code
如果出现与前面一个值相等并且前面一个值没有用到,说明选当前id的情况已经考虑过了,所以可以直接跳过。

class Solution {
    
    

    List<List<Integer>> res = new ArrayList<>();
    boolean vis[];

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
    
    
        vis = new boolean[candidates.length];
        Arrays.sort(candidates);
        List<Integer> path = new ArrayList<>();
        helper(0, target, candidates, path);
        return res;
    }

    private void helper(int id, int target, int[] nums, List<Integer> path){
    
    
        if (id == nums.length) return;
        if (target == 0){
    
    
            res.add(new ArrayList<>(path));
            return;
        }

        if (id > 0 && nums[id] == nums[id - 1] && !vis[id - 1]){
    
    
            helper(id + 1, target, nums, path);
            return;
        }

        if (target >= nums[id] && !vis[id]){
    
    
            vis[id] = true;
            path.add(nums[id]);
            helper(id, target - nums[id], nums, path);
            vis[id] = false;
            path.remove(path.size() - 1);
        }
        helper(id + 1, target, nums, path);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_50070650/article/details/112212018