Accepted simple Java solution


  • 0
    L

    Let Si be all the subsets of nums[0] ~ nums[i], then we have: Si = nums[i] + nums[i]*(Si-1) + Si-1

    public List<List<Integer>> subsets(int[] nums) {
            List<List<Integer>> res = helper(nums, nums.length-1);
            res.add(new ArrayList<>(0));
            return res;
        }
        private List<List<Integer>> helper(int[] nums, int nextIndex){
            if(nextIndex == 0){
                List<List<Integer>> subsets = new ArrayList<>();
                List<Integer> subset = Arrays.asList(nums[0]);
                subsets.add(subset);
                return subsets;
            }
            List<List<Integer>> prevSubsets = helper(nums, nextIndex-1);
            List<List<Integer>> res = new ArrayList<>();
            int nextNum = nums[nextIndex];
            res.add(Arrays.asList(nextNum));
            for(List<Integer> l : prevSubsets){
                List<Integer> copy = new ArrayList<>(l);
                copy.add(nextNum);
                res.add(copy);
            }
            res.addAll(prevSubsets);
            return res;
        }
    

Log in to reply
 

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