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> > re; vector<vector<int> > permute(vector<int> &num) { vector<int> no; vector<int> count; sort(num.begin(),num.end()); if(num.size()==0) return re; no.push_back(num[0]); count.push_back(1); int j = 0; for(int i = 1 ; i < num.size();i++) { if(num[i] == num[i-1])count[j]++; else { no.push_back(num[i]); j++; count.push_back(1); } } vector<int>temp; per(no,count,num.size(),temp,-1); return re; } void per(vector<int> no , vector<int> count, int left,vector<int>now,int should) { int i=0; if(should != -1){ now.push_back(no[should]); count[should]--; } if(left == 0) { re.push_back(now); return; } for(i=0;i<no.size();i++) { if(count[i]>0) { per(no,count,left-1,now,i); } } } };