-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path46. Permutations.java
37 lines (37 loc) · 1.2 KB
/
46. 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
33
34
35
36
37
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> permutations = new ArrayList<>();
permute(nums, permutations, 0);
return permutations;
}
private void permute(int[] nums, List<List<Integer>> permutations, int currentIndex) {
// TODO Auto-generated method stub
if (nums.length == currentIndex) {
permutations.add(toList(nums));
return;
}
for (int i = currentIndex; i < nums.length; i++) {
swap(nums, currentIndex, i);
permute(nums, permutations, currentIndex + 1);
swap(nums, currentIndex, i);
}
}
private List<Integer> toList(int[] nums) {
// TODO Auto-generated method stub
List<Integer> list = new ArrayList<>();
for (int x : nums)
list.add(x);
return list;
}
private void swap(int[] nums, int currentIndex, int i) {
// TODO Auto-generated method stub
int t = nums[currentIndex];
nums[currentIndex] = nums[i];
nums[i] = t;
}
}