Print all subsequences of a string using ArrayList in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a string and we have to print all subsequences of the string. The substring is formed by deleting elements. Also, the order of string should not be altered.

Let’s take an example to understand the problem better −

Input: string = “xyz”
Output: x y xy z xz yz xyz

To solve this problem, we will find all substring starting from freezing the first character of the string and find subsequence accordingly, then going for the next character in string and subsequence.

Example

public class Main {
   public static void printSubString(String sub,String subSeq){
      if (sub.length() == 0) {
         System.out.print(subSeq+" ");
         return;
      }
      char ch = sub.charAt(0);
      String ros = sub.substring(1);
      printSubString(ros, subSeq);
      printSubString(ros, subSeq + ch);
   }
   public static void main(String[] args){
      String str = "wxyz";
      System.out.println("The subStrings are :");
      printSubString(str, "");
   }
}

Output

The subStrings are −

z y yz x xz xy xyz w wz wy wyz wx wxz wxy wxyz
raja
Published on 17-Jan-2020 15:20:56
Advertisements