-
Notifications
You must be signed in to change notification settings - Fork 15
/
permutations.java
49 lines (41 loc) · 1.3 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
39
40
41
42
43
44
45
46
47
48
class Solution {
/**
* @param nums: A list of integers.
* @return: A list of permutations.
*/
public ArrayList<ArrayList<Integer>> permute(ArrayList<Integer> nums) {
// write your code here
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
if (nums == null || nums.size() == 0) {
return res;
}
int size = nums.size();
boolean[] used = new boolean[size];
ArrayList<Integer> tempList = new ArrayList<Integer>();
for (int i = 0; i < size; i++) {
used[i] = true;
tempList.add(nums.get(i));
dfsHelper(res, nums, used, tempList);
tempList.remove(tempList.size() - 1);
used[i] = false;
}
return res;
}
public void dfsHelper(ArrayList<ArrayList<Integer>> res, ArrayList<Integer> nums, boolean[] used, ArrayList<Integer> tempList) {
if (tempList.size() == nums.size()) {
// valid permutation.
res.add(new ArrayList<Integer>(tempList));
return;
}
for (int i = 0; i < nums.size(); i++) {
if (used[i]) {
continue;
}
used[i] = true;
tempList.add(nums.get(i));
dfsHelper(res, nums, used, tempList);
used[i] = false;
tempList.remove(tempList.size() - 1);
}
}
}