0

Given an integer n ≥ 0, count and generate all the subsets of the set {1,2,3,...,n}.

I use a stack to record the elements chosen. But how can I use a recursive function to obtain this?:

Enter an integer ≥ 0: 3 //After this part
{}
{1}
{2}
{1,2}
{3}
{1,3}
{2,3}
{1,2,3}
Number of subsets = 8 //Till before this part

Thank you for your time.

EDIT

int subset(int n){
 stack s(n);
 int n = subset(n,s);
 cout << "Number of subsets = " ;
 return n;
}

int subset(int n,stack& s){
 if(n>0)
 {
  s.push(n-1);
  int g = subset(n-1,s);
  s.pop();
  int u = subset(n-1,s);
  return g+u;
 }
}

But still not quite there. Any hints on what is wrong?

The output for 4 will be:

{}
{1}
{2}
{1,2}
{3}
{1,2}
{2,3}
{1,2,3}
{4}
{1,2}
{2,3}
{1,2,3}
{3,4}
{1,2,3}
{2,3,4}
{1,2,3,4}
user2180833
  • 156
  • 2
  • 11

0 Answers0