-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLeetcode46.java
30 lines (29 loc) · 985 Bytes
/
Leetcode46.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
public class Leetcode46 {
/**
* We need to find every premutation of given array in this question
*/
List<List<Integer>> res = new ArrayList<>();
List<Integer> list = new ArrayList<>();
public List<List<Integer>> permute(int[] nums) {
if(nums == null || nums.length == 0)return res;
dfs(nums);
return res;
}
public void dfs(int[] nums){
if(list.size() == nums.length){
// if all elements from original array is included.
// we consider it as a valid premutation.
res.add(new ArrayList<>(list));
}
for(int i = 0;i <nums.length;i++){
/**
* In this question every element is unique.
* So we our premutation already contains a element, we can skip it.
*/
if(list.contains(nums[i]))continue;
list.add(nums[i]);
dfs(nums);
list.remove(list.size()-1);
}
}
}