47. Permutations II

Backtracking

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
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
boolean[] used;

public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
int n = nums.length;
if (n == 0) return result;
used = new boolean[nums.length];
backtracking(nums);
return result;
}

private void backtracking(int[] nums) {
int n = nums.length;
if (path.size() == n) {
result.add(new ArrayList<>(path));
return;
}

for (int i = 0; i < n; i++) {
if (used[i]) continue;
if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) continue;
used[i] = true;
path.add(nums[i]);
backtracking(nums);
path.removeLast();
used[i] = false;
}
}
}

Remarks:

  1. Prunning is important: if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) continue; We skip the same items in one layer. !used[i - 1] means that we can use the duplicated number in different layers (because it was used when we call backtraking to process the next layer.)
    used[i - 1] only changes to false when a combination is fulfilled and backtracking returns.
  2. TC: $O(n!)$, SC: $O(n!\times n)$