90. Subsets II Java solution


  • 1
    R

    public class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
    List<List<Integer>> res = new ArrayList<>();
    if(nums==null||nums.length==0) return res;
    List<Integer> item = new ArrayList<>();
    Arrays.sort(nums);
    subsetsGenerator(nums, 0, res, item);
    return res;
    }

    private void subsetsGenerator(int[] nums,int from,List<List<Integer>> res, List<Integer> item) {
        if(from>=nums.length) {
            res.add(new ArrayList<Integer>(item));
            return;
        }
        int same = 0;
        while(from+same<nums.length&&nums[from+same]==nums[from]) {
            same++;
        }
        item.add(nums[from]);
        subsetsGenerator(nums,from+1,res,item);//add the number to the subset
        item.remove(item.size()-1);
        subsetsGenerator(nums,from+same,res,item);//subset not contains this number.
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.