-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPermutations.java
More file actions
48 lines (37 loc) · 1.25 KB
/
Copy pathPermutations.java
File metadata and controls
48 lines (37 loc) · 1.25 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
package Recursion;
import java.util.ArrayList;
public class Permutations {
public static void main(String[] args) {
permutations("", "abc");
System.out.println(permutationsList("", "abc"));
}
static void permutations(String p, String up){
if (up.isEmpty()){
System.out.println(p);
return;
}
char ch = up.charAt(0);
for (int i = 0; i <= p.length(); i++) {
String f= p.substring(0,i);
String s = p.substring(i, p.length());
permutations(f + ch + s, up.substring(1));
}
}
// Here a return type is ArrayList.
static ArrayList<String> permutationsList(String p, String up){
if (up.isEmpty()){
ArrayList<String> list = new ArrayList<>();
list.add(p);
return list;
}
char ch = up.charAt(0);
ArrayList<String> ans = new ArrayList<>();
for (int i = 0; i <= p.length(); i++) {
String f= p.substring(0,i);
String s = p.substring(i, p.length()); // here p.length is the ending
// so we don't need it to necessarily add this.
ans.addAll(permutationsList(f + ch + s, up.substring(1)));
}
return ans;
}
}