forked from cheungYX/algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpermutations.java
38 lines (33 loc) · 1.08 KB
/
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
38
public class Solution {
/*
* @param nums: A list of integers.
* @return: A list of permutations.
*/
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> results = new ArrayList<>();
if (nums == null) {
return results;
}
dfs(nums, new boolean[nums.length], new ArrayList<Integer>(), results);
return results;
}
private void dfs(int[] nums,
boolean[] visited,
List<Integer> permutation,
List<List<Integer>> results) {
if (nums.length == permutation.size()) {
results.add(new ArrayList<Integer>(permutation));
return;
}
for (int i = 0; i < nums.length; i++) {
if (visited[i]) {
continue;
}
permutation.add(nums[i]);
visited[i] = true;
dfs(nums, visited, permutation, results);
visited[i] = false;
permutation.remove(permutation.size() - 1);
}
}
}