larscheng / algo

0 stars 0 forks source link

【CodeTop 09】2024-09-06 - 90. 子集 II #206

Open larscheng opened 2 months ago

larscheng commented 2 months ago

90. 子集 II

larscheng commented 2 months ago

思路

回溯 题目:整数数组,包含重复,只能选一次

代码


class Solution {

    List<List<Integer>> res = new ArrayList<>();
    LinkedList<Integer> track = new LinkedList<>();

    public List<List<Integer>> subsetsWithDup(int[] nums) {
        //先将元素排序,确保重复元素都是连续的后面好剪枝
        Arrays.sort(nums);
        backtrack(nums,0);
        return  res;
    }

    private void backtrack(int[] nums, int start) {
        res.add(new ArrayList<>(track));
        for (int i = start; i < nums.length; i++) {
            if (i > start && nums[i] == nums[i - 1]) {
                //避免出现[1,2,2]中,[1,2]和[1,2]的重复现象
                continue;
            }
            track.addLast(nums[i]);
            backtrack(nums,i+1);
            track.removeLast();
        }
    }
}

复杂度