Java 15-line 2ms backtracking solution


  • 1
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        List<Integer> temp = new ArrayList<>();
        ans.add(temp);
        helper(nums,ans,temp,0);
        return ans;
    }
    //For the helper function, both of the 2 methods below will work.
    /*private void helper(int[] nums, List<List<Integer>> ans, List<Integer> last,int min){
        for(int i = min;i<nums.length;i++){
            last.add(nums[i]);
            ans.add(new ArrayList<>(last));
            helper(nums,ans,last,i+1);
            last.remove(last.size()-1); //backtracking
        }
    }*/
    private void helper(int[] nums, List<List<Integer>> ans, List<Integer> last,int min){
        for(int i = min;i<nums.length;i++){
            List<Integer> cur = new ArrayList<>(last);
            cur.add(nums[i]);
            ans.add(cur);
            helper(nums,ans,cur,i+1);
        }
    }

Log in to reply
 

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