Print all sub sequences of a given String

Objec­tive:  Given a String write an algorithm to print all the possible sub subsequences.

Example:

String input = “abc”;

Output: Possible sub sequences –
{Empty}, {a}, {b}, {c}, {ab} ,{a,c}, {b, c}, {a, b, c}

Approach:

  • The approach will be similar to as discussed here Gen­er­ate All Strings of n bits.
  • If we consider n= 3(same as the string length) then all possible combinations are [0, 0, 0] [1, 0, 0] [0, 1, 0] [1, 1, 0] [0, 0, 1] [1, 0, 1] [0, 1, 1] [1, 1, 1].
  • So from the above combinations, wherever the bit is set to 1, place an string character from index (same as position) at the position and wherever the bit is set to 0, ignore the string character at the index.
  • The above step will give the desired result.
  • See the code below for better understanding.

Time Complexity: O(2^n)

Complete Code:

public class PrintStringSubSequences {
public void printAllSubSequences(String input){
int [] temp = new int[input.length()];
int index = 0;
solve(input, index, temp);
}
private void solve(String input, int index, int [] temp){
if(index==input.length()){
print(input,temp);
return;
}
//set the current index bit and solve it recursively
temp[index] = 1;
solve(input,index+1,temp);
//unset the current index bit and solve it recursively
temp[index] = 0;
solve(input,index+1,temp);
}
private void print(String input, int [] temp){
String result = "";
for (int i = 0; i <temp.length ; i++) {
if(temp[i]==1)
result += input.charAt(i)+" ";
}
if(result=="")
result = "{Empty Set}";
System.out.println(result);
}
public static void main(String[] args) {
String input = "abc";
new PrintStringSubSequences().printAllSubSequences(input);
}
}


Output:

a b c
a b
a c
a
b c
b
c
{Empty Set}