Subsets II uses Set, subsets I uses List, 4 lines difference, iterative. Java


  • 0
    B

    For subsets I, I have:

    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        List<Integer> empty = new ArrayList<Integer>();
        result.add(empty);
        for (int i = 0; i < nums.length; i++) {
            List<List<Integer>> toAdd = new ArrayList<List<Integer>>();
            for (List<Integer> list : result) {
                List<Integer> newList = new ArrayList<Integer>(list);
                newList.add(nums[i]);
                toAdd.add(newList);
            }
            result.addAll(toAdd);
        }
        return result;
    }
    

    Compare to subsets II, I use HashSet instead:

    public List<List<Integer>> subsetsWithDup(int[] nums) {
        Set<List<Integer>> result = new HashSet<List<Integer>>();
        List<Integer> empty = new ArrayList<Integer>();
        result.add(empty);
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            Set<List<Integer>> toAdd = new HashSet<List<Integer>>();
            for (List<Integer> list : result) {
                List<Integer> newList = new ArrayList<Integer>(list);
                newList.add(nums[i]);
                toAdd.add(newList);
            }
            result.addAll(toAdd);
        }
        return new ArrayList<List<Integer>>(result);
    }

Log in to reply
 

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