Skip to content

Commit 605bc0f

Browse files
committed
LC#46 returns all permutations of given array of numbers
1 parent a256c8e commit 605bc0f

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package medium;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
public class Permutations46 {
7+
8+
public static List<List<Integer>> permute(int[] nums) {
9+
List<List<Integer>> list = new ArrayList<>();
10+
ArrayList<Integer> templist = new ArrayList<>();
11+
12+
permute(nums, templist, list);
13+
14+
return list;
15+
}
16+
17+
private static void permute(int[] nums, List<Integer> temp, List<List<Integer>> list) {
18+
19+
if (temp.size() == nums.length) {
20+
list.add(new ArrayList<>(temp));
21+
return;
22+
}
23+
24+
for (int i = 0; i < nums.length; i++) {
25+
if (temp.contains(nums[i]))
26+
continue;
27+
temp.add(nums[i]);
28+
29+
permute(nums, temp, list);
30+
31+
temp.remove(temp.size() - 1);
32+
}
33+
}
34+
35+
public static void main(String[] args) {
36+
int[] nums = { 1, 2, 3 };
37+
System.out.println(permute(nums));
38+
}
39+
}

0 commit comments

Comments
Β (0)