CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: Sets Problem

  1. #1
    Join Date
    Apr 2008
    Posts
    2

    Sets Problem

    How do you write a recursive algorithm for finding all the subsets of a given number:
    i.e if 2 is entered it should give
    1,2,12
    and if it is 3
    1,2,3,12,13,23,123

    It has to be recursive and has you are allowed to use only 1 iteration. I know how do do this non-recursively but I'm not sure how to do it recursively.

    BTW this is a console application.

    Thanks for your help!

  2. #2
    Join Date
    May 2001
    Location
    Germany
    Posts
    1,158

    Re: Sets Problem

    how do you do it without recursion? My best guess is that if you know how to do it, you only need to modify the control structure of such a program to use recursion.
    Show us what you have, maybe then you'll get a hint on how to go further.

    Richard

  3. #3
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Sets Problem

    My "all-subsets" approach has always been to assign each element to a bit, and then just count upwards to 2^n-1, using the binary representation to select elements.

    That's not recursive, though.

  4. #4
    Join Date
    Apr 2008
    Posts
    2

    Re: Sets Problem

    Well I haven't coded it using iteration but here's an explanation on how to do it:

    For a set size of 1 print all numbers upto n seperately. For set size 2, print 1 value and first value +1 then first value +2 until the end of n. then make first value , the previous first value +1 and repeat until first value is 1 less than n.

    You doa similar thing for set size 3.

    How do you code this recursively?

    Lindley: Thats the problem. It has to be done recursively. I understand the recursive relationship I just can't code it.

    Recursive relationship:

    You have to recurse on size-1 and then iterate each with a number in front. i.e.
    for an input of size 5, the size 2 array will be:

    12
    13
    14
    15
    23
    24
    25
    34
    35
    45

    the size 3 array will be:

    123
    124
    125
    134
    135
    145
    234
    235
    245
    345

    The only change is the first number in each of the lines, but I cant exactly figure out how to write the algorithm.
    Last edited by inevitable; April 3rd, 2008 at 11:45 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured