-1

I want to generate permutation of string of a given length k. Below is the code.

public class PermString {
    private static void swap(char[] a, int i, int j){
        char temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
    private static void permute(char[] a, int n){
        if(n ==1){
            System.out.println(a);
        }
        for(int i=0; i<n ; i++){
            swap(a, i, n-1);
            permute(a, n-1);
            swap(a, i, n-1);
        }
    }
    public static void main(String[] args) {
        String str = "ABCCCD";
        char[] characters = str.toCharArray();
        permute(characters, characters.length);
    }
}

It generates the permutation of string correctly, I want to know how to code the condition for fixed size length, say k.

station
  • 6,715
  • 14
  • 55
  • 89

1 Answers1

0

You just have to add another function which computes all combinations of size K --- Lets say you name it as

combGen(char[], int K)

And for each generated combination-- Compute all permutations using your existing code.

And their you would have solution. There is already an existing implementation of generating combinations, which you can have as a reference

letsBeePolite
  • 2,183
  • 1
  • 22
  • 37