Medium
Subtopics
array·backtracking·bit-manipulation
Companies
adobe·amazon·apple·atlassian·bloomberg·bytedance·coupang·ebay·facebook·goldman-sachs·google·lyft·microsoft·uber·yahooLast updated: Aug 2, 2025
If we’re given a set of integers such that S = {1, 2, 3}, how can we find all the subsets of that set? For example, given S, the set of all subsets i.e. P(S) we get are {}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, and {1, 2, 3}. Here is {} is empty set denoted by Φ.
public List<List<Integer>>subsets(int[] nums) {
List<List<Integer>> ans =new ArrayList<>();
dfs(nums, 0, ans, new ArrayList<>());
return ans;
}
privatevoiddfs(int[] nums, int idx, List<List<Integer>> ans, List<Integer> subAns) {
if (idx >= nums.length){
ans.add(new ArrayList<>(subAns));
return;
}
// include the number in the set subAns.add(nums[idx]);
dfs(nums, idx+1, ans, subAns);
// don't include the number in the set subAns.remove(subAns.size() - 1);
dfs(nums, idx+1, ans, subAns);
}
Thought Process 2 - Focus on All the Following Elements at Each Level#
Each recursion level focuses on all the following elements. We scan through all the following elements and decide whether to choose or not choose that element. (Every level split into N branches.)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public List<List<Integer>>subsets(int[] nums) {
List<List<Integer>> ans =new ArrayList<>();
Arrays.sort(nums);
backtrack(ans, new ArrayList<>(), nums, 0);
return ans;
}
privatevoidbacktrack(int[] nums, int idx, List<List<Integer>> ans , List<Integer> subAns){
ans.add(new ArrayList<>(subAns));
for(int i = idx; i < nums.length; i++){
subAns.add(nums[i]);
backtrack(nums, i + 1, ans, subAns);
subAns.remove(subAns.size() - 1);
}
}
public List<List<Integer>>subsets(int[] nums) {
int n = nums.length;
int subsetSize = (int) Math.pow(2, n); // 1 << n List<List<Integer>> ans =new ArrayList<>();
for (int i = 0; i < subsetSize; i++) {
List<Integer> single =new ArrayList<>();
for(int j = 0; j<n; j++){
// if the mask and bit are set then // we will include in the temp arr// else we will not includeif((i & (1<<j)) > 0){
single.add(nums[j]);
}
}
ans.add(single);
}
return ans;
}
1
2
Take for eg. n = 2, nums = { 10, 20};
We loop i 0 to 3, and j from 0 to nums.length.
1
2
3
4
5
6
7
8
9
i j 1 << j Set
00 0 01 []
00 1 10 [] -> added to Result
01 0 01 [10]
01 1 10 [10] -> added to Result
10 0 01 []
10 1 10 [20] -> added to Result
11 0 01 [10]
11 1 10 [10, 20] -> added to Result