Skip to content
Advertisement

How to obtain all subsequence combinations of a String (in Java, or C++ etc)

Let’s say I’ve a string “12345” I should obtain all subsequence combinations of this string such as:

  1. –> 1 2 3 4 5
  2. –> 12 13 14 15 23 24 25 34 35 45
  3. –> 123 124 125 234 235 345
  4. –> 1234 1235 1245 1345 2345
  5. –> 12345

Please note that I grouped them in different number of chars but not changed their order. I need a method/function does that.

Advertisement

Answer

You want a powerset. Here are all the questions on StackOverflow that mention powersets or power sets.

Here is a basic implementation in python:

JavaScript

And here is its output:

JavaScript

Notice that its first result is the empty set. Change the iteration from this for i in xrange(2**n): to this for i in xrange(1, 2**n): if you want to skip an empty set.

Here is the code adapted to produce string output:

JavaScript

Edit 2009-10-24

Okay, I see you are partial to an implementation in Java. I don’t know Java, so I’ll meet you halfway and give you code in C#:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement