-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy path46 Permutations
38 lines (32 loc) · 1021 Bytes
/
46 Permutations
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
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]
]
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> subset = new ArrayList();
boolean[] used = new boolean[nums.length];
dfs(subset,nums,new ArrayList(),used);
return subset;
}
void dfs( List<List<Integer>> subset,int[] nums,List<Integer> current, boolean[] used){
if(current.size()==nums.length){
subset.add(new ArrayList(current));
return;
}
for(int i=0;i<nums.length;i++){
if(used[i]==true)continue;
current.add(nums[i]);
used[i] = true;
dfs(subset,nums, current,used);
current.remove(current.size()-1);
used[i] = false;
}
}