LeetCode 90. Subsets II(子集)

原题网址:https://leetcode.com/problems/subsets-ii/

Given a collection of integers that might contain duplicates, nums, return all possible subsets.

Note:

  • Elements in a subset must be in non-descending order.
  • The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,2], a solution is:

[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

方法:深度优先搜索。

public class Solution {
    List> subsets = new ArrayList<>();
    private void swap(int[] nums, int i, int j) {
        int t = nums[i];
        nums[i] = nums[j];
        nums[j] = t;
    }
    private void subset(int[] nums, int from, int[] subs, int step, int length, List> subsets) {
        if (step == length) {
            List subset = new ArrayList<>(length);
            for(int i=0; ifrom && nums[i] == nums[i-1]) continue;
            subs[step] = nums[i];
            subset(nums, i+1, subs, step+1, length, subsets);
        }
    }
    public List> subsetsWithDup(int[] nums) {
        if (nums == null) return subsets;
        Arrays.sort(nums);
        int[] subs = new int[nums.length];
        for(int i=0; i<=nums.length; i++) subset(nums, 0, subs, 0, i, subsets);
        return subsets;
    }
}


你可能感兴趣的:(深度优先搜索,子集,幂集,组合,重复,排序,leetcode)