Pergunta de entrevista da empresa Amazon

Algorithm to produce the power set of a given set.

Respostas da entrevista

Sigiloso

23 de mar. de 2011

A set will have N elements and the number in a power set has 2^N elements, so therefore we build an array of 2^N element containers, which contain up to N elements each. We then construct a loop with a counter which starts at 0 and ends at 2^N. We do a bitwise comparison and each 1 means that we include that element in the current container index. A 0 means that we don't. For example, if our set is {A,B}, then we would have 2^2=4 possible values. We would then loop from 0 to 3. 0={}, 1={A}, 2={B}, 3={A,B}. This is the power set.

5

Sigiloso

10 de mai. de 2011

@Jordan - beautiful algorithm!