C ++中的子集II
假设我们有一组数字;我们必须生成该集合的所有可能子集。这也称为功率设定。我们必须记住,这些元素可能是重复的。因此,如果集合类似于[1,2,2],则幂集将为[[],[1],[2],[1,2],[2,2],[1,2,2]]
让我们看看步骤-
定义一个数组res和另一个数组x
我们将使用递归方法解决此问题。因此,如果将递归方法名称称为solve(),则它将使用索引,一个临时数组和数字数组(数字)
resolve()函数将如下工作:
如果index=v的大小,则
如果temp在x中不存在,则将temp插入res并将temp插入x
返回
调用solve(index+1,temp,v)
将v[index]插入temp
调用solve(index+1,temp,v)
从温度中删除最后一个元素
主要功能如下所示-
清除res和x,并对给定数组排序,定义数组temp
调用resolve(0,temp,array)
对res数组排序并返回res
让我们看下面的实现以更好地理解-
示例
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<int> > v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << "[";
for(int j = 0; j <v[i].size(); j++){
cout << v[i][j] << ", ";
}
cout << "],";
}
cout << "]"<<endl;
}
class Solution {
public:
vector < vector <int> > res;
set < vector <int> > x;
static bool cmp(vector <int> a, vector <int> b){
return a < b;
}
void solve(int idx, vector <int> temp, vector <int> &v){
if(idx == v.size()){
if(x.find(temp) == x.end()){
res.push_back(temp);
x.insert(temp);
}
return;
}
solve(idx+1, temp, v);
temp.push_back(v[idx]);
solve(idx+1, temp, v);
temp.pop_back();
}
vector<vector<int> > subsetsWithDup(vector<int> &a) {
res.clear();
x.clear();
sort(a.begin(), a.end());
vector <int> temp;
solve(0, temp, a);
sort(res.begin(), res.end(), cmp);
return res;
}
};
main(){
Solution ob;
vector<int> v = {1,2,2};
print_vector(ob.subsetsWithDup(v));
}输入值
[1,2,2]
输出结果
[[],[1, ],[1, 2, ],[1, 2, 2, ],[2, ],[2, 2, ],]