78. Subsets

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

Note: The solution set must not contain duplicate subsets.

For example, If nums = [1,2,3], a solution is:

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

BACKTRACKING

is a very important sollution:

  • sort the input to be non-descending.
  • backtracking/dfs it.

Notice, next iteration is based on current set status, not from the beginning, so the dfs will take input from i+1, not start+1.

Related Issue : 90 Subset II

public class Solution {
    public List<List<Integer>> subsets(int[] nums) {

        List<List<Integer>> res = new ArrayList<>();
        if(nums == null || nums.length == 0) return res;
        List<Integer> cur = new ArrayList<>();
        Arrays.sort(nums);
        dfs(nums, res, 0, cur);
        return res;
    }

    private void dfs(int[] nums, List<List<Integer>> res, int start, List<Integer> cur){
        res.add(new ArrayList<Integer>(cur));
        for(int i=start; i< nums.length; i++){
            cur.add(nums[i]);

            dfs(nums, res, i+1, cur); 
            cur.remove(cur.size()-1);
        }
    }
}

Solution 1. build a next set based current set, i.e. for each subset in current set, add current number, add it into the result set, as next set.

public class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();

        for(int val : nums){
            List<Integer> v = new ArrayList<>();
            v.add(val);
            List<List<Integer>> r = new ArrayList<>();

            for(List<Integer> l : res){
                List<Integer> t  = new ArrayList<>(l);
                t.addAll(v);
                r.add(t);
            }
            //you cannot update the res inside the for loop, unless you will use an iterator there.
            res.addAll(r);
            res.add(v);
        }
        res.add(new ArrayList<>());
        return res;
    }
}

results matching ""

    No results matching ""