数组的所有子集

//
// 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);
}

方法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);
}

猜你喜欢

转载自blog.csdn.net/u010325193/article/details/85546259