Print all subsequences of a string
Given a string, we have to find out all its subsequences of it. A String is a subsequence of a given String, that is generated by deleting some character of a given string without changing its order.
Examples:
Input : abc
Output : a, b, c, ab, bc, ac, abcInput : aaa
Output : a, a, a, aa, aa, aa, aaa
Method 1 (Pick and Don’t Pick Concept) :
Implementation:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;// Find all subsequencesvoid printSubsequence(string input, string output){ // Base Case // if the input is empty print the output string if (input.empty()) { cout << output << endl; return; } // output is passed with including // the Ist character of // Input string printSubsequence(input.substr(1), output + input[0]); // output is passed without // including the Ist character // of Input string printSubsequence(input.substr(1), output);}// Driver codeint main(){ // output is set to null before passing in as a // parameter string output = ""; string input = "abcd"; printSubsequence(input, output); return 0;} |
Java
// Java program for the above approachimport java.util.*;class GFG { // Declare a global list static List<String> al = new ArrayList<>(); // Creating a public static Arraylist such that // we can store values // IF there is any question of returning the // we can directly return too// public static // ArrayList<String> al = new ArrayList<String>(); public static void main(String[] args) { String s = "abcd"; findsubsequences(s, ""); // Calling a function System.out.println(al); } private static void findsubsequences(String s, String ans) { if (s.length() == 0) { al.add(ans); return; } // We add adding 1st character in string findsubsequences(s.substring(1), ans + s.charAt(0)); // Not adding first character of the string // because the concept of subsequence either // character will present or not findsubsequences(s.substring(1), ans); }} |
Python3
# Below is the implementation of the above approachdef printSubsequence(input, output): # Base Case # if the input is empty print the output string if len(input) == 0: print(output, end=' ') return # output is passed with including the # 1st character of input string printSubsequence(input[1:], output+input[0]) # output is passed without including the # 1st character of input string printSubsequence(input[1:], output)# Driver code# output is set to null before passing in# as a parameteroutput = ""input = "abcd"printSubsequence(input, output)# This code is contributed by Tharun Reddy |
C#
// C# program for the above approachusing System;using System.Collections.Generic;class GFG{static void printSubsequence(string input, string output){ // Base Case // If the input is empty print the output string if (input.Length == 0) { Console.WriteLine(output); return; } // Output is passed with including // the Ist character of // Input string printSubsequence(input.Substring(1), output + input[0]); // Output is passed without // including the Ist character // of Input string printSubsequence(input.Substring(1), output);}// Driver codestatic void Main(){ // output is set to null before passing // in as a parameter string output = ""; string input = "abcd"; printSubsequence(input, output);}} // This code is contributed by SoumikMondal |
Javascript
<script>// JavaScript program for the above approach// Find all subsequencesfunction printSubsequence(input, output){ // Base Case // if the input is empty print the output string if (input.length==0) { document.write( output + "<br>"); return; } // output is passed with including // the Ist character of // Input string printSubsequence(input.substring(1), output + input[0]); // output is passed without // including the Ist character // of Input string printSubsequence(input.substring(1), output);}// Driver code// output is set to null before passing in as a// parametervar output = "";var input = "abcd";printSubsequence(input, output);</script> |
abcd abc abd ab acd ac ad a bcd bc bd b cd c d
Method 2
Explanation :
Step 1: Iterate over the entire String
Step 2: Iterate from the end of string
in order to generate different substring
add the substring to the list
Step 3: Drop kth character from the substring obtained
from above to generate different subsequence.
Step 4: if the subsequence is not in the list then recur.Below is the implementation of the approach.
C++
// CPP program to print all subsequence of a// given string.#include <bits/stdc++.h>using namespace std;// set to store all the subsequencesunordered_set<string> st;// Function computes all the subsequence of an stringvoid subsequence(string str){ // Iterate over the entire string for (int i = 0; i < str.length(); i++) { // Iterate from the end of the string // to generate substrings for (int j = str.length(); j > i; j--) { string sub_str = str.substr(i, j); st.insert(sub_str); // Drop kth character in the substring // and if its not in the set then recur for (int k = 1; k < sub_str.length(); k++) { string sb = sub_str; // Drop character from the string sb.erase(sb.begin() + k); subsequence(sb); } } }}// Driver Codeint main(){ string s = "aabc"; subsequence(s); for (auto i : st) cout << i << " "; cout << endl; return 0;}// This code is contributed by// sanjeev2552 |
Java
// Java Program to print all subsequence of a// given string.import java.util.HashSet;public class Subsequence { // Set to store all the subsequences static HashSet<String> st = new HashSet<>(); // Function computes all the subsequence of an string static void subsequence(String str) { // Iterate over the entire string for (int i = 0; i < str.length(); i++) { // Iterate from the end of the string // to generate substrings for (int j = str.length(); j > i; j--) { String sub_str = str.substring(i, j); if (!st.contains(sub_str)) st.add(sub_str); // Drop kth character in the substring // and if its not in the set then recur for (int k = 1; k < sub_str.length() - 1; k++) { StringBuffer sb = new StringBuffer(sub_str); // Drop character from the string sb.deleteCharAt(k); if (!st.contains(sb)) ; subsequence(sb.toString()); } } } } // Driver code public static void main(String[] args) { String s = "aabc"; subsequence(s); System.out.println(st); }} |
Python3
# Python program to print all subsequence of a# given string.# set to store all the subsequencesst = set()# Function computes all the subsequence of an stringdef subsequence(str): # Iterate over the entire string for i in range(len(str)): # Iterate from the end of the string # to generate substrings for j in range(len(str),i,-1): sub_str = str[i: i+j] st.add(sub_str) # Drop kth character in the substring # and if its not in the set then recur for k in range(1,len(sub_str)): sb = sub_str # Drop character from the string sb = sb.replace(sb[k],"") subsequence(sb)# Driver Codes = "aabc"subsequence(s)for i in st: print(i,end = " ")print()# This code is contributed by shinjanpatra |
C#
using System;using System.Collections.Generic;using System.Text;public class GFG { // set to store all the subsequences public static HashSet<string> st = new HashSet<string>(); // Function computes all the subsequence of an string public static void subsequence(string str) { // Iterate over the entire string for (int i = 0; i < str.Length; i++) { // Iterate from the end of the string // to generate substrings for (int j = str.Length; j > i; j--) { string sub_str = str.Substring(i, j - i); st.Add(sub_str); // Drop kth character in the substring // and if its not in the set then recur for (int k = 1; k < sub_str.Length; k++) { string sb = sub_str; // Drop character from the string StringBuilder strBuilder = new StringBuilder(sb); strBuilder.Remove(k, 1); sb = strBuilder.ToString(); subsequence(sb); } } } } static public void Main() { string s = "aabc"; subsequence(s); foreach(var value in st) { Console.Write(value); Console.Write(" "); } }}// This code is contributed by akashish__ |
Javascript
<script>// JavaScript program to print all subsequence of a// given string.// set to store all the subsequenceslet st = new Set();// Function computes all the subsequence of an stringfunction subsequence(str){ // Iterate over the entire string for (let i = 0; i < str.length; i++) { // Iterate from the end of the string // to generate substrings for (let j = str.length; j > i; j--) { let sub_str = str.substr(i, i+j); st.add(sub_str); // Drop kth character in the substring // and if its not in the set then recur for (let k = 1; k < sub_str.length; k++) { let sb = sub_str; // Drop character from the string sb =sb.replace(sb[k],""); subsequence(sb); } } }}// Driver Codelet s = "aabc";subsequence(s);for (let i of st) document.write(i," ");document.write("</br>");// This code is contributed by shinjanpatra</script> |
aab aa aac bc b abc aabc ab ac a c
Method 3: One by one fix characters and recursively generates all subsets starting from them. After every recursive call, we remove last character so that the next permutation can be generated.
Implementation:
C++
// CPP program to generate power set in// lexicographic order.#include <bits/stdc++.h>using namespace std;// str : Stores input string// n : Length of str.// curr : Stores current permutation// index : Index in current permutation, currvoid printSubSeqRec(string str, int n, int index = -1, string curr = ""){ // base case if (index == n) return; if (!curr.empty()) { cout << curr << "\n"; } for (int i = index + 1; i < n; i++) { curr += str[i]; printSubSeqRec(str, n, i, curr); // backtracking curr = curr.erase(curr.size() - 1); } return;}// Generates power set in lexicographic// order.void printSubSeq(string str){ printSubSeqRec(str, str.size());}// Driver codeint main(){ string str = "cab"; printSubSeq(str); return 0;} |
Java
// Java program to generate power set in// lexicographic order.class GFG { // str : Stores input string // n : Length of str. // curr : Stores current permutation // index : Index in current permutation, curr static void printSubSeqRec(String str, int n, int index, String curr) { // base case if (index == n) { return; } if (curr != null && !curr.trim().isEmpty()) { System.out.println(curr); } for (int i = index + 1; i < n; i++) { curr += str.charAt(i); printSubSeqRec(str, n, i, curr); // backtracking curr = curr.substring(0, curr.length() - 1); } } // Generates power set in // lexicographic order. static void printSubSeq(String str) { int index = -1; String curr = ""; printSubSeqRec(str, str.length(), index, curr); } // Driver code public static void main(String[] args) { String str = "cab"; printSubSeq(str); }}// This code is contributed by PrinciRaj1992 |
Python3
# Python program to generate power set in lexicographic order. # str: Stores input string # n: Length of str. # curr: Stores current permutation # index: Index in current permutation, currdef printSubSeqRec(str, n, index = -1, curr = ""): # base case if (index == n): return if (len(curr) > 0): print(curr) i = index + 1 while(i < n): curr = curr + str[i] printSubSeqRec(str, n, i, curr) curr = curr[0:-1] i = i + 1 # Generates power set in lexicographic order.# functiondef printSubSeq(str): printSubSeqRec(str, len(str))# // Driver codestr = "cab"printSubSeq(str)# This code is contributed by shinjanpatra |
C#
// Include namespace systemusing System;// C# program to generate power set in// lexicographic order.public class GFG{ // str : Stores input string // n : Length of str. // curr : Stores current permutation // index : Index in current permutation, curr public static void printSubSeqRec(String str, int n, int index, String curr) { // base case if (index == n) { return; } if (curr != null && !(curr.Trim().Length == 0)) { Console.WriteLine(curr); } for (int i = index + 1; i < n; i++) { curr += str[i]; GFG.printSubSeqRec(str, n, i, curr); // backtracking curr = curr.Substring(0,curr.Length - 1-0); } } // Generates power set in // lexicographic order. public static void printSubSeq(String str) { var index = -1; var curr = ""; GFG.printSubSeqRec(str, str.Length, index, curr); } // Driver code public static void Main(String[] args) { var str = "cab"; GFG.printSubSeq(str); }}// This code is contributed by mukulsomukesh |
Javascript
<script>// JavaScript program to generate power set in// lexicographic order. // str : Stores input string// n : Length of str.// curr : Stores current permutation// index : Index in current permutation, currfunction printSubSeqRec(str,n,index = -1,curr = ""){ // base case if (index == n) return; if (curr.length>0) { document.write(curr) } for (let i = index + 1; i < n; i++) { curr += str[i]; printSubSeqRec(str, n, i, curr); // backtracking curr = curr.slice(0, - 1); } return;} // Generates power set in lexicographic// order.function printSubSeq(str){ printSubSeqRec(str, str.length);} // Driver codelet str = "cab";printSubSeq(str);</script> |
c ca cab cb a ab b
Time Complexity: O(n * 2n), where n is the size of the given string
Auxiliary Space: O(n), due to recursive call stack
Method 4: Using Binary representation of numbers to create Subsequences
String = “abc”
All combinations of abc can be represented by all binary representation from 0 to (2^n – 1) where n is the size of the string . The following representation clears things up.
Note : We can also take zero into consideration which will eventually give us an empty set “” , the only change in code will be starting loop from zero.
001 -> “c”
010 -> “b”
011 -> “bc
100 -> “a”
101 -> “ac”
110 -> “ab”
111 -> “abc”
As you can observe we get unique sub-sequences for every set-bit and thus no 2 combinations can be same as 2 numbers cannot have same binary representation.
Input : “abc”
Output :
a
b
a b
c
a c
b c
a b c
Implementation :
1. We take the string as input.
2. We declare a vector of strings to store each sub-sequence as a string.
3. Each time call the function with 1,2,3 and so on and we only push those indexes in our string whose bit is set and we keep incrementing our index pointer.
4. Once we have generated the corresponding sub-sequence for a binary representation we can push this string into our vector of strings.
5. Finally we can print our vector of strings and get the desired output.
C++
#include<bits/stdc++.h>using namespace std;string print(string s , int i){ int j = 0; string sub; //finding where the bit is set while(i>0){ if(i & 1){ sub.push_back(s[j]); //pushing only when bit is set } j++; //always incrementing the index pointer i = i >> 1; } return sub;}vector<string> createsubsets(string& s){ vector <string> res; for(int i = 1 ; i <= ((1 << s.size()) - 1) ; i++){ //each time we create a subsequence for corresponding binary representation res.push_back(print(s,i)); } return res;}int main(){ string s = "abcd"; //vector of strings to store all sub-sequences vector <string> print = createsubsets(s); //print function for(int i = 0 ; i < print.size() ; i++){ for (int j = 0; j < print[i].size(); j++){ cout << print[i][j]<<" "; } cout << endl; } return 0;} |
a b a b c a c b c a b c
This article is contributed by Sumit Ghosh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.






Please Login to comment...