How to print distinct permutations of a string in java

Printing distinct permutations of a string in Java can be achieved using a combination of recursion and backtracking. Here's a step-by-step guide to implement this in Java:

  1. Create a method that accepts a string and an index as arguments. This method will be used to generate the permutations of the string.

  2. Check if the index is equal to the length of the string. If it is, print the string and return.

  3. Iterate through the string starting from the index. For each character, swap it with the character at the index.

  4. Recursively call the method with the index + 1 as the new index.

  5. After the recursive call, swap the characters back to their original positions to backtrack and generate other permutations.

  6. Keep a set to store the permutations, to avoid printing duplicates.

  7. Finally, call the method with an index of 0 to start generating the permutations.

Here's a sample code that implements the above steps:

 

import java.util.HashSet;
import java.util.Set;

public class Main {
    static Set set = new HashSet<>();
    
    static void permute(char[] str, int index) {
        if (index == str.length) {
            set.add(String.valueOf(str));
            return;
        }
        
        for (int i = index; i < str.length; i++) {
            swap(str, index, i);
            permute(str, index + 1);
            swap(str, index, i);
        }
    }
    
    static void swap(char[] str, int i, int j) {
        char temp = str[i];
        str[i] = str[j];
        str[j] = temp;
    }
    
    public static void main(String[] args) {
        String s = "abc";
        permute(s.toCharArray(), 0);
        set.forEach(System.out::println);
    }
}

This code will print the distinct permutations of the string "abc". The permutations are stored in a set to avoid duplicates.

 

Submit Your Programming Assignment Details