链接: https://oj.leetcode.com/problems/permutations/


每次从num中选择一个数添加到结果中,并用used标记用过的数.

public class Solution {
	private boolean used[];
	private  List<List<Integer> > ans;
	private  List<Integer> tans ;
	public  List<List<Integer> > permute(int[] num)
	{
		used=new boolean[num.length];
		ans=new ArrayList<List<Integer>>();
		tans=new ArrayList<Integer>() ;
		for(int i=0;i<used.length;i++)
			used[i]=false;
		my_next_permute(0,num.length,num);
		return ans;
	}
	public void my_next_permute(int pos,int n,int[] num)
	{
		
		if(pos==n)	
		{
			ans.add(new ArrayList<Integer>(tans));
			
			return ;
		}
		for(int i=0;i<n;i++)
		{
			if(!used[i])
			{
				tans.add(new Integer(num[i]));
				used[i]=true;
				my_next_permute(pos+1,n,num);
				tans.remove(tans.size()-1);
				used[i]=false;
			}
		}
	return;
	}
};

C++的STL中有next_permutation()函数,可以求出下一个全排列


class Solution
{
	public:
		vector<vector<int> > permute(vector<int> &num)
		{
			vector<vector<int> > ans;
			sort(num.begin(),num.end());
			ans.push_back(num);
			while(next_permutation(num.begin(),num.end()))
			{
				ans.push_back(num);
			}
			return ans;

		}
};