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], and [3,2,1].
Classical backtrack.
In order to make the output in sequence, sort the inputs first.
void permute(vector<int>& nums, int depth, vector<vector<int>>& res, vector<int>& path, vector<int>& used) {
if(depth == nums.size()) res.push_back(path); // depth variable can be saved, if here checks path.size() == nums.size()
for(int i = 0; i < nums.size(); ++i) {
if(used[i] == false) {
used[i] = true; // use a flag to mark that the value has been used.
path.push_back(nums[i]);
permute(nums, depth + 1, res, path, used);
used[i] = false;
path.pop_back();
}
}
}
vector<vector<int>> permute(vector<int>& nums) {
if(nums.size() == 0) return {};
sort(nums.begin(), nums.end());
vector<vector<int>> res;
vector<int> path;
vector<int> used(nums.size(), false);
permute(nums, 0, res, path, used);
return res;
}

本文介绍了一个经典的排列生成算法实现,该算法通过递归回溯的方式,对给定的一组不重复数字生成所有可能的排列组合,并确保输出结果有序。文章提供了详细的C++代码示例,演示如何使用标记数组避免元素重复使用。
706

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



