给定一个没有重复数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/permutations
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法:
利用DFS,结合回溯法
class Solution {
void dfs(vector<int> nums, vector<int> curVec, vector<vector<int>>& res){
if (curVec.size() == nums.size()){
res.push_back(curVec);
return ;
}
for (int i = 0; i< nums.size(); i++) {
if(find(curVec.begin(), curVec.end(), nums[i]) == curVec.end()) {
curVec.push_back(nums[i]);
dfs(nums, curVec, res);
curVec.pop_back();
}
}
}
public:
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> res;
if(nums.size() == 0)
return res;
vector<int> curVec;
dfs(nums, curVec, res);
return res;
}
};
方法二:
通过回溯法的思想,使用交换操作实现
class Solution {
void swap(int& num1, int& num2){
int tmp = num2;
num2 = num1;
num1 = tmp;
}
void backtrack(vector<int>& nums, vector<vector<int>>& res, int curPos){
if (curPos == nums.size()){
res.push_back(nums);
return ;
}
for (int i = curPos; i < nums.size(); i++) {
swap(nums[curPos], nums[i]);
backtrack(nums, res, curPos + 1);
swap(nums[curPos], nums[i]);
}
}
public:
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> res;
if(nums.size() == 0)
return res;
backtrack(nums, res, 0);
return res;
}
};