数组的所有子集

 

//
// Created by dongfucai on 2019/1/1.
//

#include <vector>
#include <iostream>

using namespace std;

class Solution {
public:
    void solve(vector<int> &ivec) {
        if (ivec.size() == 0) {
            return;
        }
        
        vector<int> temp;
        vector<vector<int> > res;
        int n = ivec.size();
        int pos = 0;
        dfs(ivec, res, temp, pos, n);
        for (int i = 0; i < res.size(); ++i) {
            for (int j = 0; j < res[i].size(); ++j) {
                cout << res[i][j] << " ";
            }
            cout << endl;
        }
    }

    void dfs(vector<int> &ivec, vector<vector<int> > &res, vector<int> temp, int pos, int &n) {
        if (pos == n) {
            res.push_back(temp);
            return;
        }
        res.push_back(temp);

        for (int i = pos; i < n; ++i) {
            temp.push_back(ivec[i]);
            dfs(ivec, res, temp, i + 1, n);
            temp.pop_back();
        }
    }
};

int main () {
    Solution s;
    int a[] = {10, 11, 12};
    vector<int> ivec(a, a + 3);
    s.solve(ivec);
}

 

class Solution {
public:
    vector<vector<int> > subsets(vector<int> &S) {
        vector<int> temp;
        dfs(S,temp,S.size(),0);
        
        return res;
    }
    
      vector<vector<int> > res;
    void dfs(vector<int> &ivec,vector<int> temp,int n,int pos){
		
  //      if(temp.size()==k){
  //          res.push_back(temp);
		//	for_each(temp.begin(),temp.end(),print());
  //          return ;
		//}
	if(pos==n){
            res.push_back(temp);
            return ;
	}
        
        res.push_back(temp);
		   //for_each(temp.begin(),temp.end(),print());
		   //cout<<endl;
		
        for(int i=pos;i<n;++i){
            temp.push_back(ivec[i]);
            dfs(ivec,temp,n,i+1); // pos+1 是有重复的  i+1 是一直往上走的
            temp.pop_back();
        }
    }
};

 

方法2

void subsets(vector<int> &S,vector<int> temp,int level,vector<vector<int> > &result)
{
    //如果是叶子节点则加入到result中
    if(level == S.size())
    {
        result.push_back(temp);
        return;
    }
    //对于非叶子节点,不将当前元素加入到temp中
    subsets(S,temp,level + 1,result);
    //将元素加入到temp中
    temp.push_back(S[level]);
    subsets(S,temp,level + 1,result);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值