Subsets Leetcode


#1

Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: nums = [1,2,3]
Output:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

#2

The below code uses backtracking to form all the subsets possible for a given list of elements.

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        backtrack(nums, 0, new ArrayList<Integer>(), result);
        return result;
    }
    
    private void backtrack(int[] nums, int start, List<Integer> cur, List<List<Integer>> result){
        result.add(new ArrayList<>(cur));
        for(int i=start;i<nums.length;i++){
            cur.add(nums[i]);
            backtrack(nums, i+1, cur, result);
            cur.remove(cur.size()-1);
        }
    }
}