forked from algorithm009-class01/algorithm009-class01
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPermute.java
More file actions
41 lines (37 loc) · 1.15 KB
/
Permute.java
File metadata and controls
41 lines (37 loc) · 1.15 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
package recur;
import java.util.ArrayList;
import java.util.List;
public class Permute {
public List<List<Integer>> permute(int[] nums){
int len = nums.length;
List<List<Integer>> res = new ArrayList<>();
if (len == 0){
return res;
}
boolean[] used = new boolean[len];
List<Integer> path = new ArrayList<>();
dfs(nums,len,0,path,used,res);
return res;
}
private void dfs(int[] nums, int len, int depth, List<Integer> path, boolean[] used, List<List<Integer>> res) {
if (depth == len){
res.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < len; i++) {
if (!used[i]){
path.add(nums[i]);
used[i] = true;
dfs(nums,len,depth+1,path,used,res);
used[i] = false;
path.remove(path.size() - 1);
}
}
}
public static void main(String[] args) {
int[] nums = {1,2,3};
Permute permute = new Permute();
List<List<Integer>> lists = permute.permute(nums);
System.out.println(lists);
}
}