forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0046-permutations.java
32 lines (27 loc) · 829 Bytes
/
0046-permutations.java
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
importjava.util.ArrayList;
importjava.util.Arrays;
classSolution {
publicList<List<Integer>> permute(int[] nums) {
List<List<Integer>> ans = newArrayList<>();
function(ans, nums, 0);
returnans;
}
publicvoidfunction(List<List<Integer>> ans, int[] arr, intstart) {
if (start == arr.length) {
List<Integer> list = newArrayList();
for (inti = 0; i < arr.length; i++) list.add(arr[i]);
ans.add(list);
return;
}
for (inti = start; i < arr.length; i++) {
swap(arr, start, i);
function(ans, arr, start + 1);
swap(arr, start, i);
}
}
publicvoidswap(int[] arr, inta, intb) {
inttemp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
}