Permutations II

Leetcode 47.

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
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
int numsLength = nums.length;
List<List<Integer>> ans = new ArrayList<>();
List<Integer> list = new ArrayList<Integer>();
if(numsLength == 1){
list.add(nums[0]);
ans.add(list);
return ans;
}
boolean[] visited = new boolean[numsLength];

Arrays.sort(nums);
backtricking(nums,ans,list,visited);
return ans;
}
public void backtricking(int[] nums, List<List<Integer>> ans,List<Integer> list,boolean[] visited){
//recursion stop condition
if(list.size() == nums.length){
//collect the results
ans.add(new ArrayList<>(list));
return;
}

//for loop for this layer
for(int i = 0; i < nums.length;i++){
//avoid the duplicate cases
if(i != 0 && nums[i] == nums[i - 1] && !visited[i - 1])
continue;
//avoid elements that have already been passed
if(visited[i])
continue;

visited[i] = true;
list.add(nums[i]);
//recursion
backtricking(nums,ans,list,visited);
//undo the previous operation
list.remove(list.size() - 1);
visited[i] = false;
}

}

}