有一个递增有序整数序列,其中元素可能重复出现,求其所有的子集(结果中不能有两个相同的子集),例如 s={1,2,2},输出结果是“{},{1},{1,2},{1,2,2},{2},{2,2}”(顺序不重要)。
代码如下:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class solution
{
private:
vector<int> path;
vector<vector<int>> result;
public:
void backtrace(const vector<int>& nums, int start)
{
if (start==nums.size())return;
for (int i = start; i<nums.size(); i++)//nums={1,2,2,2}时,i最大到3
{
if(i!=0){ if (nums[i] == nums[i - 1] && i > start)continue; } //此处的if(i!=0)是当start=0时,i被start赋值后以防后面nums[i-1]发生下标超出范围
path.push_back(nums[i]);
result.push_back(path);
backtrace(nums, i + 1);
path.pop_back();
}
}
vector<vector<int>> solve(vector<int>& nums)
{
sort(nums.begin(), nums.end());
result.push_back(path);//此处是先把空集合放进result
backtrace(nums, 0);
return result;
}
};
void outputVector_2D(vector<vector<int>>& output_result)
{
cout << endl;
for (vector<vector<int>>::iterator i = output_result.begin(); i != output_result.end(); i++)
{
vector<int> temp = *i;
cout << "{ ";
for (vector<int>::iterator j = temp.begin(); j != temp.end(); j++)
{
cout << *j;
if (j != temp.end() - 1)
{
cout << ",";
}
}
cout << " }";
cout << endl;
}
}
int main()
{
vector<int> nums;
vector<vector<int>> main_result;
solution sol;
int length; cin >> length;
for (int i=0;i<length;i++)
{
int t; cin >> t;
nums.push_back(t);
}
main_result=sol.solve(nums);
outputVector_2D(main_result);
}
效果展示:
下面的图片仅供参考(作者用来记忆的草稿,在练字)