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

Viewed 32912

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.

13 Answers
public class Sub {

    public static void main(String[] args) {
          String str="ADDIS";
          Sub.DisplaySubsequence( str.toCharArray(), 
          str.toCharArray().length,0 );
     }
     public static void DisplaySubsequence(char[] set, int n, int index){
         
        if(n>index){
            
                String x =String.valueOf(set[index]);
                System.out.println(x);
                String concat=x;
                for(int j=index+1; j<n; j++){
                        concat=concat.concat(String.valueOf(set[j]));
                        System.out.println(concat);
                 }
                 DisplaySubsequence(set, n,index+1);
         }
         
            return 0;
         
    }
}
Related