Algo-Sim › Recursion & Backtracking
Permutations II
Medium · Recursion & Backtracking · step through it in Java, Python and C++ on your own input
Every distinct ordering when values repeat: sort, then skip a value whose equal twin to the left is still unused.
Problem
Given a collection of numbers nums that might contain duplicates, return all possible unique permutations in any order.
Constraints
- 1 ≤ nums.length ≤ 8
- -10 ≤ nums[i] ≤ 10
- Values may repeat
Edge cases to test
- All values equal: one permutation
- Two distinct values repeated
- One element
Follow-up questions
- Why skip when the left twin is unused?
- It forces equal values to appear in left-to-right order, so each distinct arrangement is built once.
- What is the counting alternative?
- Backtrack over a count map of distinct values instead of positions: the same output with no sort or skip rule.
Solution
Java
List<List<Integer>> result = new ArrayList<>();
List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
backtrack(nums, new boolean[nums.length], new ArrayList<>());
return result;
}
void backtrack(int[] nums, boolean[] used, List<Integer> path) {
if (path.size() == nums.length) {
result.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < nums.length; i++) {
if (used[i]) continue;
// A twin that is still unused means this value was already tried here.
if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) continue;
used[i] = true;
path.add(nums[i]);
backtrack(nums, used, path);
path.remove(path.size() - 1);
used[i] = false;
}
}Python
def permute_unique(nums):
nums = sorted(nums)
result = []
used = [False] * len(nums)
def backtrack(path):
if len(path) == len(nums):
result.append(path[:])
return
for i in range(len(nums)):
if used[i]:
continue
# A twin that is still unused means this value was already tried here.
if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]:
continue
used[i] = True
path.append(nums[i])
backtrack(path)
path.pop()
used[i] = False
backtrack([])
return resultC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<vector<int>> result = {};
vector<vector<int>> permuteUnique(vector<int> &nums) {
sort(nums.begin(), nums.end());
vector<int> path;
vector<bool> used(nums.size());
backtrack(nums, used, path);
return result;
}
void backtrack(vector<int> &nums, vector<bool> &used, vector<int> &path) {
if (int(path.size()) == int(nums.size())) {
result.push_back(path);
return;
}
for (int i = 0; i < int(nums.size()); i++) {
if (used[i])
continue;
// A twin that is still unused means this value was already tried here.
if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1])
continue;
used[i] = true;
path.push_back(nums[i]);
backtrack(nums, used, path);
path.pop_back();
used[i] = false;
}
}
};
More Recursion & Backtracking problems
- Fibonacci Number (Easy)
- Tower of Hanoi (Medium)
- Generate Parentheses (Medium)
- Subsets (Medium)
- Subsets II (Medium)
- Permutations (Medium)
- Combinations (Medium)
- Letter Combinations of a Phone Number (Medium)
- Combination Sum (Medium)
- Combination Sum II (Medium)
- Palindrome Partitioning (Medium)
- Restore IP Addresses (Medium)
- Word Break II (Hard)
- Remove Invalid Parentheses (Hard)
- Word Search (Medium)
- N-Queens (Hard)
- Sudoku Solver (Hard)