Permutations


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].

class Solution {
public:
   vector<vector<int> > permute(vector<int> &num) {
		vector<vector<int>> all;
		for(size_t i=0;i<num.size();++i){
			vector<int> copyRest(num.begin(),num.end());
			copyRest.erase(copyRest.begin()+i);
			vector<vector<int>> rest= permute(copyRest);
			if(rest.size()==0){
				all.push_back(num);
			}else{
				for(size_t j=0;j<rest.size();++j){
					vector<int> &each=rest[j];
					each.insert(each.begin(),num[i]);
					all.push_back(each);
				}
			}
		}
		return all;
	}
};

你可能感兴趣的:(Permutations)