目录
1. 全排列(去重)
void dfs(const vector<int>& nums, int pos, vector<vector<int>>& result, vector<int>& cur) {
if (pos == nums.size()) {
result.push_back(cur);
return;
}
for (int i = 0; i < nums.size(); ++i) {
// 当上一位释放的数字和这一位数字相同时,会产生相同的排列
if (Visited[i] || (i > 0 && nums[i] == nums[i - 1] && !Visited[i - 1])) {
continue;
}
Visited[i] = true;
cur.push_back(nums[i]);
dfs(nums, pos + 1, result, cur);
cur.pop_back();
Visited[i] = false;
}
}
vector<vector<int>> permuteUnique(vector<int>& nums) {
vector<vector<int>> result;
vector<int> cur;
// 全排列去重前提,排序后的数组
sort(nums.begin(), nums.end());
dfs(nums, 0, result, cur);
return result;
}
2. 子集
void subset(const vector<int>& nums, int n, vector<vector<int>>& result, vector<int>& tmp) {
if (n < 0) {
result.push_back(tmp);
return;
}
tmp.push_back(nums[n]);
subset(nums, n - 1, result, tmp);
tmp.pop_back();
subset(nums, n - 1, result, tmp);
}
3. 集合分割
void segment(string n, int pos, vector<vector<string>>& res, vector<string>& cur) {
if (pos == n.size()) {
res.push_back(cur);
return;
}
for (int i = pos; i < n.size(); ++i) {
string s;
for (int j = pos; j <= i; ++j) {
s += n[j];
}
cur.push_back(s);
segment(n, i + 1, res, cur);
cur.pop_back();
}
}
标签:分割,排列,cur,nums,pos,back,vector,result,集合
From: https://www.cnblogs.com/linukey/p/17418446.html