1. 程式人生 > >[LeetCode]47. Permutations II && DFS及剪枝

[LeetCode]47. Permutations II && DFS及剪枝

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

For example,
[1,1,2] have the following unique permutations:

[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]

Subscribe to see which companies asked this question

#include<iostream>
#include<vector>
#include<cstring>
#include<iterator>
#include<algorithm>
using namespace std;
void DFS(vector<vector<int> > &res,vector<int> &temp,int *visit,vector<int>& nums)
{
	if(nums.size() == temp.size()){
    	
	    res.push_back(temp);
	    return;
    }
    for(int i = 0;i < nums.size();i++)
    {	
    	if(i!=0&&nums[i]==nums[i-1]&&visit[i-1]==0)   //剪枝  有序陣列與前一個數相等且前一個數未被訪問過
    		continue;
    	if(visit[i]==0)
    	{
    		visit[i]=1;
    		temp.push_back(nums[i]);
    	    DFS(res,temp,visit,nums);
    	    temp.pop_back();
    	    visit[i]=0;
    	}
    }
	
}
vector<vector<int> > permuteUnique(vector<int>& nums) {
	vector<vector<int> > res;
	int len=nums.size();
	int *visit=new int[len];
	if(len==0)
		return res;
	vector<int> temp;
	sort(nums.begin(),nums.end());
	memset(visit,0,len*sizeof(int));
	DFS(res,temp,visit,nums);	
	return res;
}

int main()
{
    vector<int> num;
    num.push_back(2);
    num.push_back(2);
    num.push_back(2);
    num.push_back(4);
    vector<vector<int> > permutes = permuteUnique(num);
    for(int i = 0;i < permutes.size();i++){
        cout<<"[";
        for(int j = 0;j < permutes[i].size();j++){
            cout<<permutes[i][j];
        }//for
        cout<<"]"<<endl;
    }
    return 0;
}