题目:
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>> result;
vector<vector<int>> tmp_result;
if(num.size() == 1) {
result.push_back(num);
return result;
}
for(int i = 0; i < num.size(); i++) {
vector<int> tmp_num = num;
tmp_num.erase(tmp_num.begin()+i);
tmp_result = permute(tmp_num);
for(int j = 0; j < tmp_result.size(); j++) {
tmp_result[j].insert(tmp_result[j].begin(), num[i]);
result.push_back(tmp_result[j]);
}
}
return result;
}
};
思路:
递归,比如运行permute([1,2,3,4]),则会先后运行permute([2,3,4])、permute([1,3,4])、permute([1,2,4])、permute([1,2,3]),值得确定的是,运行permute([2,3,4])一定会返回2、3、4的全排列,然后在2、3、4的全排列的各个元素前插入1,即是1、2、3、4的一组全排列。