Bitmask
What does bitmask do?
Bitmask is a way to brute force all subsets. It can also be used for other purposes, but that is its' main function.
Let's look at an example problem
Example Problem
You are given a set of integers
We can solve this problem by brute forcing all possible subsets. However, you might notice that you would need
Bitmask
We can represent every subset as an array
For example, suppose my subset contains elements
Hence, we can loop through all the binary numbers from
Coding Bitmask
int ans = 0;
for (int i = 0; i < 1 << n; ++i) {
int sum = 0;
for (int j = 0; j < n; ++j) {
if (i & (1 << j)) {
sum += arr[j];
}
}
if (sum <= k) {
ans = max(ans, sum);
}
}
Let's analyse what the code below is doing
for (int j = 0; j < n; ++j) {
if (i & (1 << j)) {
sum += arr[j];
}
}
Essentially
i & (1 << j)
will be larger than
So, the code is just doing if the
The rest should be self explanatory