[LeetCode] 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 =
If nums =
[1,2,3]
, a solution is:[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
Thought process:
Iterate through the list. For each number, iterate through the list again starting from that element. As I iterate, add elements to the current list. Delete the last added element after the recurrence.
Solution 1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public class Solution { public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> subsets = new ArrayList<>(); List<Integer> subset = new ArrayList<>(); subsets(nums, 0, subset, subsets); return subsets; } private void subsets(int[] nums, int start, List<Integer> subset, List<List<Integer>> subsets) { subsets.add(new ArrayList<>(subset)); for (int i = start; i < nums.length; i++) { subset.add(nums[i]); subsets(nums, i + 1, subset, subsets); subset.remove(subset.size() - 1); } } } |
Another way to do this is bit manipulation. For example, if there are three numbers in the array, the number of subsets will be eight. Choosing which number goes to which subset is like flipping bits. There are three numbers so I have three bits 0 0 0. The 0th subset has nothing. The first subset only has the first number 0 0 1. The second subset only has the second number 0 1 0... The 7th subset has all three numbers 1 1 1.
So I will use a nested for loop. The outer loop iterate through the numbers. The inner loop checks if the current bit pattern includes current number.
Solution 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public class Solution { public List<List<Integer>> subsets(int[] nums) { int length = nums.length; int size = (int) Math.pow(2, length); List<List<Integer>> subsets = new ArrayList<>(); for (int i = 0; i < size; i++) { subsets.add(new ArrayList<>()); } for (int i = 0; i < length; i++) { for (int j = 0; j < size; j++) { if ((j >> i & 1) == 1) { subsets.get(j).add(nums[i]); } } } return subsets; } } |
Time complexity:
A set with n elements has 2^n subsets. The overall time complexity is O(2^n).
Comments
Post a Comment