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:

  1. [
  2. [3],
  3. [1],
  4. [2],
  5. [1,2,3],
  6. [1,3],
  7. [2,3],
  8. [1,2],
  9. []
  10. ]

Solution:

  1. public class Solution {
  2. public List<List<Integer>> subsets(int[] nums) {
  3. List<List<Integer>> res = new ArrayList<List<Integer>>();
  4. res.add(new ArrayList<Integer>());
  5. Arrays.sort(nums);
  6. for (int i = 0; i < nums.length; i++) {
  7. int size = res.size();
  8. for (int j = 0; j < size; j++) {
  9. List<Integer> sol = new ArrayList<Integer>(res.get(j));
  10. sol.add(nums[i]);
  11. res.add(sol);
  12. }
  13. }
  14. return res;
  15. }
  16. }