//78. Subsets
Given a set of distinct integers, nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,3], a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int> > subsets(vector<int>& nums) {
res.clear();
if(nums.size()==0){
return res;
}
vector<int> s;
for(int i=0;i<nums.size();i++){
findNext(nums,0,i,s);
}
res.push_back(nums);
return res;
}
private:
vector<vector<int> > res;
//s saved 0---start-1,nums ,search new element from start
void findNext(vector<int>& nums,int start,int k,vector<int>& s){
if(s.size()==k){
res.push_back(s);
return;
}
for(int i=start;i<nums.size();i++){
//deal with the i element
s.push_back(nums[i]);
//dela with the i+1 element
findNext(nums,i+1,k,s);
s.pop_back();
}
return;
}
};
int main(){
int arr[]={1,2,3,4};
vector<int> nums(arr,arr+sizeof(arr)/sizeof(int));
vector<vector<int> > res=Solution().subsets(nums);
for(int i=0;i<res.size();i++){
for(int j=0;j<res[i].size();j++){
cout<<res[i][j]<<" ";
}
cout<<endl;
}
return 0;
}