Permutation II
Link: https://leetcode.com/problems/permutations-ii/
Constraint:
- Arrays may not be sorted
- May contain duplicate
- Return order is arbitrary
Idea
The difference with Permutation I is how to avoid adding duplicate permutations. Based on the graph below, each permutation can be seen as a path from root to bottom. We only continue to add numbers at index i to the permutation if the conditionas are met:
- nums[i] is not visited;
- nums[i] == nums[i - 1];
- nums[i - 1] is also not visited.
Take the path [b, a, c] as an example. When b is not visited, a is also not visited. If we continue on this path, it would yield the same permutation as the path [a, b, c].
Code
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> results = new ArrayList<>();
Arrays.sort(nums);
boolean[] visited = new boolean[nums.length];
search(nums, visited, new ArrayList<Integer>(), results);
return results;
}
private void search(int[] nums, boolean[] visited, List<Integer> perm, List<List<Integer>> results) {
if (perm.size() == nums.length) {
results.add(new ArrayList<>(perm));
return;
}
for (int i = 0; i < nums.length; i++) {
if (visited[i] || (i > 0 && nums[i] == nums[i - 1] && visited[i - 1])) {
continue;
}
visited[i] = true;
perm.add(nums[i]);
search(nums, visited, perm, results);
perm.remove(perm.size() - 1);
visited[i] = false;
}
}
}
- Time: O(n * n!). When there's no duplicates, there are at most n! permutations. Copying each permutation takes O(n).
- Space: O(n!) which is equal to the number of permutations.
Reference: http://www.jiuzhang.com/solutions/permutations-ii/
浙公网安备 33010602011771号