Java 10 lines solution neither recursive nor bit manipulation


  • 1
        public List<List<Integer>> subsets(int[] nums) {
            List<List<Integer>> list = new ArrayList<>();
            list.add(new ArrayList<>());
            for (int i = 0, pow = 1; i < nums.length; i++, pow *= 2) {
                for (int j = 0; j < pow; j++) {
                    List<Integer> l = new ArrayList<>(list.get(j));
                    l.add(nums[i]);
                    list.add(l);
                }   
            }   
            return list;
        } 
    

    If there are duplicates then we can use the following version:

        public List<List<Integer>> subsetsWithDup(int[] nums) {
            Arrays.sort(nums);
            List<List<Integer>> list = new ArrayList<>();
            list.add(new ArrayList<>());
            for (int i = 0, begin = 0, size = list.size(); i < nums.length; i++, begin = size, size = list.size()) {
                for (int j = i > 0 && nums[i] == nums[i - 1] ? begin : 0; j < size; j++) {
                    List<Integer> l = new ArrayList<>(list.get(j));
                    l.add(nums[i]);
                    list.add(l);
                }   
            }   
            return list;
        } 
    

  • 0
    J

    @皮皮鲁 said in Java 10 lines solution neither recursive nor bit manipulation:

    List<Integer> l = new ArrayList<>(list.get(j));

    Could you please explain this part of the code? what is the significance of list.get(j)?


Log in to reply
 

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