Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

java - Best recursive algorithm to print out subsets

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...