The problem “Permutations II” from LeetCode requires generating all unique permutations of a given list of numbers that might contain duplicates. The result should not contain any duplicate permutations.
Example:
Input: nums = [1,1,2]
Output:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
visited
array to keep track of used elements and avoid using the same element more than once at the same position in different recursive calls.Here is the C++ implementation:
#include <vector>
#include <algorithm>
class Solution {
public:
std::vector<std::vector<int>> permuteUnique(std::vector<int>& nums) {
std::vector<std::vector<int>> result;
std::vector<int> current;
std::vector<bool> visited(nums.size(), false);
// Sort the nums array to handle duplicates
std::sort(nums.begin(), nums.end());
// Begin backtracking process
backtrack(nums, current, visited, result);
return result;
}
private:
void backtrack(std::vector<int>& nums, std::vector<int>& current, std::vector<bool>& visited, std::vector<std::vector<int>>& result) {
// Base case: if current permutation is complete
if (current.size() == nums.size()) {
result.push_back(current);
return;
}
for (int i = 0; i < nums.size(); ++i) {
// Skip used elements and duplicates
if (visited[i] || (i > 0 && nums[i] == nums[i-1] && !visited[i-1])) {
continue;
}
// Include this element in the current permutation
visited[i] = true;
current.push_back(nums[i]);
// Recurse to build all possible permutations
backtrack(nums, current, visited, result);
// Backtrack: undo the choice
current.pop_back();
visited[i] = false;
}
}
};
The time complexity of generating all unique permutations is determined by the number of permutations and the cost to generate each one. In the worst case:
n
distinct elements are (n!). However, with duplicates, this number decreases, but the upper bound remains (n!).Thus, the overall time complexity is (O(n \log n + n! \cdot n)):
Therefore, the combined time complexity is effectively (O(n \cdot n!)) in the worst case.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?