Given a sequence that can contain repeated numbers , Returns all non repeating full permutations .
Examples :
input : [1,1,2] output : [ [1,1,2], [1,2,1], [2,1,1] ]
Thinking analysis : The difference between this question and the last one is that there are repeated elements in the array , Therefore, the emphasis of this topic is to remove the duplicate . If you have no idea about this topic , There are many ways to do it online , You can browse them all , Find the best way for yourself .
use dfs The code is as follows :
class Solution {
public:
vector<vector<int>>result;// For holding, so the answer
void dfs(vector<int>& nums,vector<int>& temp,vector<bool>& sign)
{
if(temp.size()==nums.size())// If temp I put it in nums All elements in , It means that we have found an answer that satisfies the conditions
result.push_back(temp);
else
{
for(int i=0;i<nums.size();i++)
{
if(sign[i]==false)// If it's been used , skip
continue;
// If you repeat the number in front of him , And the number in front of you should also participate in the arrangement , Because there is only one arrangement for the two repeated numbers , The first time the recursion reaches the end point, it will be liberated to the solution set , So skip
if(i>0&&nums[i]==nums[i-1]&&sign[i-1]==true)
continue;
//
temp.push_back(nums[i]);// New elements put temp in , Construct solution
sign[i]=false;// Indicates that it has been used
dfs(nums,temp,sign); Recursion continues to find the elements that make up the solution
// There are no elements available to make up the solution , After getting a solution , Look back to see if there are any unsolved solutions in the previous step
temp.pop_back();
sign[i]=true;
//
}
}
}
vector<vector<int>> permuteUnique(vector<int>& nums) {
vector<int> temp;// Temporary array , A solution satisfying a condition
vector<bool>sign(nums.size(),true);// Used to mark whether this has been used
sort(nums.begin(),nums.end());// Sorting makes it easy for us to remove the duplicate
dfs(nums,temp,sign);
return result;
}
};
Technology
Daily Recommendation