-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpermutationString.java
More file actions
37 lines (31 loc) · 1.06 KB
/
permutationString.java
File metadata and controls
37 lines (31 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.io.*;
import java.util.*;
public class permutationString {
//swap function to swap two characters from indices idx and idx2
public static void swap(char[] arr, int idx, int idx2) {
char temp = arr[idx];
arr[idx] = arr[idx2];
arr[idx2] = temp;
}
public static void solve(char[] arr, int idx) {
if (idx == arr.length - 1) { //Base condition of recursion
System.out.print(String.valueOf(arr) + " ");
}
for (int i = idx; i < arr.length; i++) {
swap(arr, idx, i);
solve(arr, idx + 1);
swap(arr, idx, i);
//Backtracking: reverting all the elements to their original places
}
}
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
System.out.print("Enter string to generate its permutations: ");
String str = scn.next(); //String input from the user
if (str.length() == 0 || str == null) {
return;
}
solve(str.toCharArray(), 0); //function call to find all the permutations
//toCharArray() converts a given string into a character array
}
}