如果不包含重复元素,那么所有排列可以按如下方式进行打印
#include<bits/stdc++.h>
class Solution {
public:
void dfs(vector<int>vec, int cur, vector<vector<int>>&ans){
if (cur == vec.size()-1){
ans.push_back(vec);
return;
}
for(int i = cur; i < vec.size(); ++i){
//if(i != cur and vec[i] == vec[cur]) continue;
swap(vec[i], vec[cur]);
dfs(vec, cur + 1, ans);
}
}
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>>ans;
//sort(nums.begin(), nums.end());
dfs(nums, 0, ans);
return ans;
}
};
如果包含重重元素,则需要先排序,再把重复的元素所在的区间当作一个来做
#include<bits/stdc++.h>
class Solution {
public:
void dfs(vector<int>vec, int cur, vector<vector<int>>&ans){
if (cur == vec.size()-1){
ans.push_back(vec);
return;
}
for(int i = cur; i < vec.size(); ++i){
if(i != cur and vec[i] == vec[cur]) continue;
swap(vec[i], vec[cur]);
dfs(vec, cur + 1, ans);
}
}
vector<vector<int>> permuteUnique(vector<int>& nums) {
vector<vector<int>>ans;
sort(nums.begin(), nums.end());
dfs(nums, 0, ans);
return ans;
}
};