Simple Java Solution Similar to SubSet I

  • 0
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> list = new ArrayList<>();
        list.add(new ArrayList<>());
        if(nums.length == 0) return list;
        list.add(new ArrayList<>(Arrays.asList(nums[0])));
        int prevNum = nums[0], prevIndex = 1;
        for(int i=1; i<nums.length; i++) {
            List<List<Integer>> oldList = new ArrayList<>(list);
            int count = 0;
            for(int j=(nums[i]==prevNum?prevIndex:0); j<oldList.size(); j++) {
                List<Integer> tempList = new ArrayList<>(oldList.get(j));
            // if new element equals to this one, you need to modify list from this position
            prevIndex = list.size() - count;
            prevNum = nums[i];
        return list;

    This approach is very similar to the one of Subset I, the only difference is the store the index information when you find the new number equals to the previous one.

Log in to reply

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