LeetCode.90. 子集 II

90. 子集 II

难度:meidum

LeetCode.90. 子集 II_第1张图片

 本题和LeetCode.40. 组合总和 II可以说一模一样:

 方法一:使用startIndex确认是当前树层来去重

class Solution {
    private List> ans = new ArrayList<>();
    private List path = new ArrayList<>();
    public List> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
        backtracking(nums, 0);
        return ans;
    }
    public void backtracking(int[] nums, int startIndex) {
        ans.add(new ArrayList<>(path));
        if (startIndex >= nums.length) {
            return;
        }
        for (int i = startIndex; i < nums.length; i++) {
            if (i > startIndex && nums[i] == nums[i - 1]) {
                continue;
            }
            path.add(nums[i]);
            backtracking(nums, i + 1);
            path.remove(path.size() - 1);
        }
    }
}

方法二:使用used数组

class Solution {
    private List> ans = new ArrayList<>();
    private List path = new ArrayList<>();
   
    public List> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
        boolean[] used = new boolean[nums.length];
        backtracking(nums, 0, used);
        return ans;
    }
    public void backtracking(int[] nums, int startIndex, boolean[] used) {
        ans.add(new ArrayList<>(path));
        if (startIndex >= nums.length) {
            return;
        }
        for (int i = startIndex; i < nums.length; i++) {
            if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false) {
                continue;
            }
            path.add(nums[i]);
            used[i] = true;
            backtracking(nums, i + 1, used);
            path.remove(path.size() - 1);
            used[i] = false;
        }
    }
}

你可能感兴趣的:(#,回溯,LeetCode,java,leetcode,开发语言)