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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<int> > res;
vector<int> rcd;
subPermute(res, num, rcd);
return res;
}
void subPermute(vector<vector<int> > &res, vector<int> &num, vector<int> &rcd){
if(num.size() == 0){
res.push_back(rcd);
return;
}
for(int i = 0; i < num.size(); ++i){
vector<int> temp = num;
rcd.push_back(temp[i]);
for(int j = i; j < num.size() -1 ;++j){
temp[j] = temp[j+1];
}
temp.pop_back();
subPermute(res, temp, rcd);
rcd.pop_back();
}
}
};