Generate Permutations without Repetition
This program generates permutations of a string without repeating characters.
Problem Statement
Write a Java program to generate permutations of "ABA" without repetition.
Source Code
| 1 | import java.util.HashSet; |
| 2 | public class PermutationsNoRepetition { |
| 3 | public static void permute(String str, String ans, HashSet<String> set){ |
| 4 | if(str.length()==0){ |
| 5 | if(!set.contains(ans)){ |
| 6 | System.out.println(ans); |
| 7 | set.add(ans); |
| 8 | } |
| 9 | return; |
| 10 | } |
| 11 | for(int i=0;i<str.length();i++){ |
| 12 | char ch=str.charAt(i); |
| 13 | String ros=str.substring(0,i)+str.substring(i+1); |
| 14 | permute(ros,ans+ch,set); |
| 15 | } |
| 16 | } |
| 17 | public static void main(String[] args) { |
| 18 | System.out.println("Eduinq Permutations No Repetition"); |
| 19 | permute("ABA","",new HashSet<>()); |
| 20 | } |
| 21 | } |
Program Output
Eduinq Permutations No Repetition ABA AAB BAA
Explanation
The same recursive permutation approach is used, but a HashSet tracks already-printed results so that duplicate permutations arising from repeated characters are filtered out, demonstrating permutation generation without repetition.