Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to find a good recursive algorithm to print out the subsets of a set. For example

size 5: gives the set {1,2,3,4,5} and the subsets off length 3 gives this output:

{5,4,3}
{5,4,2}
{5,4,1}
{5,3,2}
{5,3,1}
{5,2,1}
{4,3,2}
{4,3,1}
{4,2,1}
{3,2,1}

I've tried many things but it doesn't work. On the internet all the examples are with sets algorithms but I want to write my own, for learning purposes.

Could someone help me with this?

Kind regards,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
227 views
Welcome To Ask or Share your Answers For Others

1 Answer

To construct a recursive algorithm you can notice that each subset of length 3 from {1,2,3,4,5} either:

  • Contains the element "1" and 2 elements from {2,3,4,5}.
  • Doesn't contains the element "1" and 3 elements from {2,3,4,5}.

Each of these two cases can be implemented by calling your function recursively.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...