Mental Model
We find every possible group of items from a list, including empty and full groups.
Analogy: Imagine you have a box of colored beads and want to see all ways you can pick some beads or none at all.
Set: [1, 2] Subsets: [] [1] [2] [1, 2]
Set: [1, 2] Subsets: [] [1] [2] [1, 2]
[]
[] [1]
[] [1] [2] [1, 2]
[] [1] [2] [1, 2]
import java.util.*; public class Powerset { public static List<List<Integer>> generateSubsets(int[] nums) { List<List<Integer>> result = new ArrayList<>(); result.add(new ArrayList<>()); // start with empty subset for (int num : nums) { int size = result.size(); for (int i = 0; i < size; i++) { List<Integer> newSubset = new ArrayList<>(result.get(i)); newSubset.add(num); // add current number to existing subset result.add(newSubset); // add new subset to result } } return result; } public static void main(String[] args) { int[] input = {1, 2}; List<List<Integer>> subsets = generateSubsets(input); for (List<Integer> subset : subsets) { System.out.println(subset); } } }
result.add(new ArrayList<>()); // start with empty subsetfor (int num : nums) {int size = result.size();for (int i = 0; i < size; i++) {List<Integer> newSubset = new ArrayList<>(result.get(i));newSubset.add(num); // add current number to existing subsetresult.add(newSubset); // add new subset to resultresult.add(new ArrayList<>()); // start with empty subsetfor (int num : nums) {
powerset mean in the context of subsets?public static List subsets(int[] nums) {
List result = new ArrayList<>();
result.add(new ArrayList<>());
for (int num : nums) {
int size = result.size();
for (int i = 0; i < size; i++) {
List<Integer> subset = new ArrayList<>(result.get(i));
subset.add(num);
result.add(subset);
}
}
return result;
}
// Called with nums = {1, 2}public static List subsets(int[] nums) {
List result = new ArrayList<>();
for (int num : nums) {
int size = result.size();
for (int i = 0; i < size; i++) {
List<Integer> subset = new ArrayList<>(result.get(i));
subset.add(num);
result.add(subset);
}
}
result.add(new ArrayList<>());
return result;
}nums that may contain duplicates, which modification to the standard subsets generation algorithm ensures the powerset contains no duplicate subsets?Pass the test and this pattern moves unknown