Very simple java recursive solution


  • 0
    G

    public class Solution {

    public List<List<Integer>> subsets(int[] nums) {
        Arrays.sort(nums);
        return subsets(nums, nums.length - 1);
    }
    

    // the following function returns the subset result of subarray of nums[0, ..., bound], which includes all the elements in the subset of nums[0, ..., bound -1], and the result of adding nums[bound] to those elements.

    public List<List<Integer>> subsets(int[] nums, int bound){
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        if(result == null){ return result;}
        if(bound == 0){
            List<Integer> temp = new ArrayList<Integer>();
            temp.add(nums[0]);
            result.add(temp);
            result.add(new ArrayList<Integer>());
            return result;
        }
        List<List<Integer>> pre = subsets(nums, bound-1);
        for(int i = 0; i < pre.size(); i++){
            List<Integer> temp = new ArrayList<Integer>(pre.get(i));
            temp.add(nums[bound]);
            result.add(temp);
        }
        result.addAll(pre);
        return result;
    }
    

    }


Log in to reply
 

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