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> >ret;
int n=num.size();
_permute(num,n,n-1,ret);
return ret;
}
void _permute(vector<int>& array,int n,int depth,vector<vector<int> >&ret){
if(depth==0){
ret.push_back(array);
return;
}
for(int i=0 ; i<=depth ; i++){
swap(array[i],array[depth]);
_permute(array,n,depth-1,ret);
swap(array[i],array[depth]);
}
return;
}
};
本文介绍了一种使用递归实现的简单方法来获取一个整数集合的所有可能排列。通过交换元素并递归调用自身来生成所有可能的排列组合。
391

被折叠的 条评论
为什么被折叠?



