Subsets with a Catch

In his programming class, Rishabh is asked to implement a program that takes in a set S S of n n distinct integers and output all possible subsets of S S .

However, the catch is that he is asked not to use recursive functions.

Using which data structure makes more sense for Rishabh to solve this problem?

Binary Search Tree Hash Table Queue Stack

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

1 solution

The natural way to answer this problem is this:

  • The power set of the empty set is just { ϕ } \left \{ \phi \right \} .
  • Otherwise, we can choose whether the first element is in a particular set or isn't and then we've reduced the problem to a set with n 1 n-1 elements.
1
2
3
4
5
6
7
8
9
def subsets(L):
    if L == []:
        return [[]]
    setsWithX = []
    setsWithoutX = []
    for l in subsets(L[1:]):
        setsWithX.append([L[0]] + l)
        setsWithoutX.append(l)
    return setsWithX + setsWithoutX

Since function calls themselves are implemented within the memory using a stack, it is possible to use stacks to implement the behaviour of recursion.

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...