Popular Posts

Monday, July 18, 2011

PowerSet

Problem:
Write a method that returns all subsets of a set.
Solution:
Recursive approach:

  • The set of subsets of {1} is {{}, {1}}
  • For {1, 2}, take {{}, {1}}, add 2 to each subset to get {{2}, {1, 2}} and take the union with {{}, {1}} to get {{}, {1}, {2}, {1, 2}}
  • Repeat till you reach n

Complexity: O(2^n)
Code:

Iterative Approach:

No comments:

Post a Comment