Enumerate a subset of a number

1

Enumerate a subset of n, where k is the number of bits of n

void hh(int n){
    for (int i=n; i; i=(i-1)&n) printf("%d ",i);
}
  • The time complexity is the number of subsets of n, which is less than 2^k.
  • Easy to prove (refer to the proof method below)

2

Enumerate all subsets of all subsets of n

void hh(int n){
    for (int i=n; i; i=(i-1)&n) hh(i);
}
  • The time complexity is less than 3^k.
  • Proof
    provided enumerate the subset of n m, then m enumerated subset of s;
    for a certain number s i on, only the following three cases, so the total time complexity is the 3 ^ k:
i&n i&m
1 1
1 0
0 0

3

Enumerate a subset of a subset of a subset of n... The
program and so on, the time complexity is similar, but it does not seem to be very useful.

application

http://uoj.ac/contest/43/problem/370
can look at this question, clever use of enumerated subsets to reduce time complexity.

Guess you like

Origin blog.csdn.net/jackypigpig/article/details/79660522