algorithm - How to generate a power set of a given set? -
i studying interview , stumbled upon question online under "math" category.
generate powerfulness set of given set:
int a[] = {1,2,3,4,5}; int n = 5; int total = 1 << n; ( int = 0; < total; i++ ) { ( int j = 0; j < n; j++) { if ( (i >> j) & 1 ) cout << a[j]; } cout <<endl; } please not want explicit answer. want clarifications , hints on how approach problem.
i checked powerfulness set algorithm on google , still not understand how address problem.
also, reiterate question asking for.
thank you.
power set of set set of of subsets of a.
not friendly definition in world, illustration help :
eg. {1, 2}, subsets : {}, {1}, {2}, {1, 2}
thus, powerfulness set {{}, {1}, {2}, {1, 2}}
generate powerfulness set, observe how create subset : go each element 1 one, , either retain or ignore it.
let decision indicated bit (1/0).
thus, generate {1}, pick 1 , drop 2 (10).
on similar lines, can write bit vector subsets :
{} -> 00 {1} -> 10 {2} -> 01 {1,2} -> 11to reiterate : subset if formed including or of elements of original set. thus, create subset, go each element, , decide whether maintain or drop it. means each element, have 2 decisions. thus, set, can end 2^n different decisions, corresponding 2^n different subsets.
see if can pick here.
algorithm math powerset
No comments:
Post a Comment