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> > ans;
vector<int> v;
bool *nums;
int len;
vector<vector<int> > permute(vector<int> &num) {
len = num.size();
nums = new bool[len];
for(int i = 0;i < len;i ++)
nums[i] = true;
dfs(num);
return ans;
}
void dfs(vector<int> &num){
if(v.size() == len){
ans.push_back(v);
return;
}
for(int i = 0;i < len;i ++){
if(nums[i]){
v.push_back(num[i]);
nums[i] = false;
dfs(num);
nums[i] = true;
v.pop_back();
}
}
}
};
本文介绍了一个通过深度优先搜索(DFS)实现的排列算法。该算法能够找出给定数字集合的所有可能排列,并详细展示了如何使用布尔数组跟踪已使用元素,避免重复排列。
1825

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



