陣列的所有子集
阿新 • • 發佈:2019-01-04
// // 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); }