1. 题目
Given a collection of distinct 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],
[3,2,1]
]
2. 思路
递归方式。分为[0][1~N)两个数组,后者递归得到一个集合。
前者插入到后者每一个结果的里的每一个位置中。
3. 代码
耗时:13ms
class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
return permute(nums, 0);
}
vector<vector<int>> permute(vector<int>& nums, int beg) {
int sz = nums.size();
vector<vector<int>> ret;
if (sz == beg) { return ret; }
if (sz == beg + 1) {
vector<int> one;
one.push_back(nums[beg]);
ret.push_back(one);
return ret;
}
vector<vector<int>> subs = permute(nums, beg+1);
// 将nums[beg]插入到subs的所有结果的所有位置
int beg_v = nums[beg];
for (int i = 0; i < subs.size(); i++) {
vector<int>& vec_i = subs[i];
for (int j = 0; j <= vec_i.size(); j++) { // j表示插入的位置
vector<int> cat;
for (int k = 0; k <= vec_i.size(); k++) {
if (k == j) {
cat.push_back(beg_v);
} else if (k < j) {
cat.push_back(vec_i[k]);
} else {
cat.push_back(vec_i[k-1]);
}
}
ret.push_back(cat);
}
}
return ret;
}
};