Tuesday, February 13, 2018

Backtracking 2 - Generate all combinations of String characters for n digits.

"For a given String of n characters length, generate all combinations for k digits"

Using recursive procedure, we can generate all possible combinations.

Input :
  • String of length n will be given
  • k - digits for which the combinations need to be generated.
For Eg, if String s = "ab", the combinations are "aa, ab, bb, ba"

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
public class StringPermutationUsingRecursion{

    public static void main(String args[]){
        String s = "ab";
        int k = 3;
        StringPermutationUsingRecursion permutation = new StringPermutationUsingRecursion();        
        permutation.printAllString(s,"", k);
    }
    public void printAllString(String s,String suffix, int k){

        if(k <1 ){
            System.out.println(suffix);
            return;
        }   else {
            for(int i = 0; i < s.length();i++){
                String newsuffix = suffix+s.charAt(i);
                printAllString(s,newsuffix, k-1);
            }
        }
    }    
}

 The algorithm goes as below,

1. Iterate over given string, form a substring 
2. Recursively call the function until the k is less than 1.
3. Print the substring when k reaches 0 or less than 1.

The order or sequence which we generate manually may change. 

No comments:

Post a Comment

Reading and Writing JSON to a file

Why GSON? Nowadays JSON is more frequently used for data representation. There are a lot of libraries to convert java objects into JSO...