Skip to content

Commit 866b757

Browse files
MEDIUM/src/medium/Permutations.java using regular recursive method
1 parent 47eea51 commit 866b757

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

MEDIUM/src/medium/Permutations.java

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package medium;
2+
import java.util.ArrayList;
3+
import java.util.List;
4+
5+
public class Permutations {
6+
static class Accepted_solution {
7+
//this solution has a recursive function that has a return type
8+
public static List<List<Integer>> permute(int[] nums) {
9+
List<List<Integer>> result = new ArrayList();
10+
result.add(new ArrayList<>());
11+
return recursive(result, nums, 0);
12+
}
13+
14+
private static List<List<Integer>> recursive(List<List<Integer>> result, int[] nums,
15+
int pos) {
16+
if (pos == nums.length)
17+
return result;
18+
List<List<Integer>> newResult = new ArrayList();
19+
for (List<Integer> eachList : result) {
20+
for (int i = 0; i <= eachList.size(); i++) {
21+
List<Integer> newList = new ArrayList(eachList);
22+
newList.add(i, nums[pos]);
23+
newResult.add(newList);
24+
}
25+
}
26+
result = newResult;
27+
return recursive(result, nums, pos + 1);
28+
}
29+
}
30+
31+
static class Accepted_solution_with_void_type {
32+
public static List<List<Integer>> permute(int[] nums) {
33+
List<List<Integer>> result = new ArrayList();
34+
result.add(new ArrayList<>());
35+
recursive(result, nums, 0);
36+
return result;
37+
}
38+
39+
private static void recursive(List<List<Integer>> result, int[] nums, int pos) {
40+
if(pos == nums.length) return;
41+
List<List<Integer>> newResult = new ArrayList();
42+
for(List<Integer> eachList : result){
43+
for(int i = 0; i <= eachList.size(); i++){
44+
List<Integer> newList = new ArrayList(eachList);
45+
newList.add(i, nums[pos]);
46+
newResult.add(newList);
47+
}
48+
}
49+
/**You'll have to use the two lines, instead of this line: result = newResult; otherwise, it won't work!!! Fuck!*/
50+
result.clear();
51+
result.addAll(newResult);
52+
53+
//then recursion
54+
recursive(result, nums, pos+1);
55+
}
56+
}
57+
58+
public static void main(String...args){
59+
int[] nums = new int[]{1,2,2};
60+
}
61+
62+
}

0 commit comments

Comments
 (0)