-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrintPermutationsOfAString.java
More file actions
50 lines (44 loc) · 1.06 KB
/
PrintPermutationsOfAString.java
File metadata and controls
50 lines (44 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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Print Permutations of a String
// Hard
// Score
// 0/600
// Average time to solve is 60m
// Problem statement
// Given a string, find and print all the possible permutations of the input
// string.
// Note :
// The order of permutations are not important. Just print them in different
// lines.
// Sample Input :
// abc
// Sample Output :
// abc
// acb
// bac
// bca
// cab
// cba
public class solution {
public static void permutations(String input) {
// Write your code here
helper(input.toCharArray(), 0);
}
// Helper
public static void helper(char arr[], int index) {
if (index == arr.length - 1) {
System.out.println(new String(arr));
} else {
for (int i = index; i < arr.length; i++) {
swap(arr, index, i);
helper(arr, index + 1);
swap(arr, index, i);
}
}
}
// Swapping the elements
public static void swap(char[] arr, int i, int j) {
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}