生成全排列的经典问题,递归方法的典范。
bool visited[10000];
void getPermutation(vector<int> &num, vector<vector<int> > &res, vector<int> &pres, int len, int p){
if(p == len){
res.push_back(pres);
return;
}
for(int i=0;i<len;i++){
if(!visited[i]){
visited[i] = 1;
pres[p] = num[i];
getPermutation(num, res, pres, len, p+1);
visited[i] = 0;
}
}
}
class Solution {
public:
vector<vector<int> > permute(vector<int> &num) {
int msize = num.size();
vector<vector<int> > res;
vector<int> pres(msize);
if(msize == 0)
return res;
memset(visited, 0, sizeof(visited));
getPermutation(num, res, pres, msize, 0);
return res;
}
};