Generate All Permutations of String

This program generates all permutations of a string.

Problem Statement

Write a Java program to generate all permutations of "ABC".

Source Code

1 public class StringPermutations {
2 public static void permute(String str, String ans){
3 if(str.length()==0){
4 System.out.println(ans);
5 return;
6 }
7 for(int i=0;i<str.length();i++){
8 char ch=str.charAt(i);
9 String ros=str.substring(0,i)+str.substring(i+1);
10 permute(ros,ans+ch);
11 }
12 }
13 public static void main(String[] args) {
14 System.out.println("Eduinq String Permutations");
15 permute("ABC","");
16 }
17 }

Program Output

Eduinq String Permutations
ABC
ACB
BAC
BCA
CAB
CBA

Explanation

The recursive function chooses each character in turn to add to the answer so far, then recursively permutes the remaining string, together generating and printing every possible permutation.

Quick Links to Explore