Permutations

难度:2

Given a collection of numbers, return all possible permutations.

For example,
[1,2,3] have the following permutations:
[1,2,3][1,3,2][2,1,3][2,3,1][3,1,2], and [3,2,1].

找到所有排列,DFS,久不写裸搜,居然写错了两次。。。

class Solution 
{
public:
	vector<vector<int> > ans;
	vector<int>tmp;
	vector<bool>flag;
	vector<int>a;
	int n;
	void dfs(int index)
	{
		if(index == n)	{ans.push_back(tmp);return;}
		for(int i=0;i<n;i++)
		{
			if(flag[i])	continue;
			tmp.push_back(a[i]);
			flag[i]=true;
			dfs(index+1);
			tmp.pop_back();
			flag[i]=false;
		}
	}
    vector<vector<int> > permute(vector<int> &num) 
	{
		ans.clear();
		tmp.clear();
		a.assign(num.begin(),num.end());
		n=num.size();
		flag.assign(n,false);
		dfs(0);
		return ans;
    }
};


你可能感兴趣的:(Permutations)