Question same as in the title.
I’ve done two approaches. One is straightforward.
Generate all bitmasks from
2^{n-1}
to
2^n
And for every bitmask check if there is same amount 1’s and 0’s, if yes, work on it.
And that’s the problem, because i have to work on those bitmasks not only count them.
I came with second approach which runs on O(2^{n/2}) time, but seems like it’s not generating all bitmasks and i don’t know why.
Second approach is like that :
generate all bitmasks from 0 to 2^{n/2} and to have valid bitmask( call it B ) i have to do something like this : B#~B
where ~ is negative.
So for example i have n=6, so i’m going to generate bitmasks with length of 3.
For example i have B=101, so ~B will be 010
and final bitmask would be 101010, as we see, we have same amount of 1’s and 0’s.
Is this method good or am i implementing something bad ? Maybe some another interesting approach exist?
Thanks
Chris
Try a recursive approach:
Call
printMaskspassing it the desired number of 0’s and 1’s. For example, if you need 3 ones and 3 zeros, call it like this: