C++ 子集 II
假设我们有一组数字;我们必须生成该集合的所有可能的子集。这也被称为幂集。我们必须记住元素可能是重复的。因此,如果集合类似于 [1,2,2],则幂集将为 [[], [1], [2], [1,2], [2,2], [1,2,2]]
让我们看看步骤:
- 定义一个数组 res 和另一个名为 x 的集合
- 我们将使用递归方法解决这个问题。因此,如果递归方法名称称为 solve(),并且它接受索引、一个临时数组和数字数组 (nums)
- solve() 函数的工作方式如下:
- 如果索引 = v 的大小,则
- 如果 temp 不存在于 x 中,则将 temp 插入 res 并将 temp 插入 x
- 返回
- 调用 solve(index + 1, temp, v)
- 将 v[index] 插入 temp
- 调用 solve(index + 1, temp, v)
- 从 temp 中删除最后一个元素
- 主函数如下:
- 清除 res 和 x,并对给定数组进行排序,定义一个数组 temp
- 调用 solve(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, ],]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP