Subsets via bitmask
Generate every subset of a small array by reading each number from 0 to 2^n - 1 as a bitmask of inclusions.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
Each of the n elements is either in a subset or not, which is exactly one bit of information, so every subset corresponds to a unique n-bit number. Counting mask from 0 to 2^n - 1 visits every combination of bits exactly once, and bit i of mask says whether a[i] belongs to that subset.
Code
public static List<List<int>> SubsetsByBitmask(int[] a) {
var result = new List<List<int>>();
int n = a.Length;
for (int mask = 0; mask < (1 << n); mask++) {
var subset = new List<int>();
for (int i = 0; i < n; i++)
if ((mask & (1 << i)) != 0)
subset.Add(a[i]);
result.Add(subset);
}
return result;
}static List<List<Integer>> subsetsByBitmask(int[] a) {
List<List<Integer>> result = new ArrayList<>();
int n = a.length;
for (int mask = 0; mask < (1 << n); mask++) {
List<Integer> subset = new ArrayList<>();
for (int i = 0; i < n; i++)
if ((mask & (1 << i)) != 0)
subset.add(a[i]);
result.add(subset);
}
return result;
}vector<vector<int>> subsetsByBitmask(const vector<int>& a) {
vector<vector<int>> result;
int n = a.size();
for (int mask = 0; mask < (1 << n); mask++) {
vector<int> subset;
for (int i = 0; i < n; i++)
if ((mask & (1 << i)) != 0)
subset.push_back(a[i]);
result.push_back(subset);
}
return result;
}def subsets_by_bitmask(a: list[int]) -> list[list[int]]:
result = []
n = len(a)
for mask in range(1 << n):
subset = []
for i in range(n):
if mask & (1 << i) != 0:
subset.append(a[i])
result.append(subset)
return resultTips
- mask & (1 << i) tests bit i without disturbing the other bits.
- mask = 0 always gives the empty subset and mask = 2^n - 1 always gives the full set.
In the .NET library
This is the same search space as the recursive Subsets lesson in Backtracking; the bitmask version just enumerates it iteratively instead of with recursive choices.