-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy path46.permutations.java
More file actions
48 lines (40 loc) · 1.16 KB
/
46.permutations.java
File metadata and controls
48 lines (40 loc) · 1.16 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
/* 46. Permutations
Given a collection of distinct integers, return all possible permutations.
Example:
Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
*/
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if (nums == null || nums.length == 0)
return res;
boolean[] used = new boolean[nums.length];
List<Integer> permutation = new ArrayList<>();
helper(nums,permutation,used,res);
return res;
}
private void helper(int[] nums, List<Integer> permutation, boolean[] used, List<List<Integer>> res){
if(permutation.size () == nums.length) {
res.add(new ArrayList<>(permutation)); //deep copy
return;
}
for (int i = 0; i < nums.length; i++) {
if (used[i])
continue; //skip if already seen this num
used[i] = true;
permutation.add(nums[i]);
helper(nums, permutation, used, res);
permutation.remove(permutation.size()-1);
used[i] = false;
}
}
}