Subsets

Given a set of distinct integers, return all possible subsets.

  • Elements in a subset must be in non-descending order.
  • The solution set must not contain duplicate subsets.

Example:

If S = [1,2,3], a solution is:

[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

Solution:

We could use depth first to solve it.

Code:

class Solution {

    public ArrayList<ArrayList<Integer>> subsets(int[] nums) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        if (nums == null || nums.length == 0) {
            return res;
        }
        ArrayList<Integer> path = new ArrayList<>();
        Arrays.sort(nums);
        helper(nums, 0, path, res);
        return res;
    }
    private void helper(int[] nums, int index, ArrayList<Integer> path, 
                    ArrayList<ArrayList<Integer>> res) {
        res.add(new ArrayList<>(path));
        for (int i = index; i < nums.length; i++)  {
            path.add(nums[i]);
            helper(nums, i + 1, path, res);
            path.remove(path.size() - 1);
        }
    }
}

Additional solution:

public List<List<Integer>> subsets(int[] S) {  
    List<List<Integer>> result = new ArrayList<>();  
    Arrays.sort(S);  
    int n = S.length;  
    int size = (int)Math.pow(2, n);  
    for(int i=0; i<size; i++) {  
        List<Integer> list = new ArrayList<>();  
        for(int j=0; j<n; j++) {  
            if((i>>>j & 1) == 1) {  
                list.add(S[j]);  
            }
        }  
        result.add(list);  
    }  
    return result;  
}

results matching ""

    No results matching ""