n个数取k个的集合
自己写的代码:
class Solution { public: vector<int>v1; vector<vector<int>>v; vector<vector<int>> combine(int n, int k) { v.clear(); vector<int>exist(n,0); add(exist,n,k,0); return v; } void add(vector<int>&exist,int n,int k,int cur) { if(cur<n) { exist[cur]=1; add(exist,n,k,cur+1); exist[cur]=0; add(exist,n,k,cur+1); } if(cur==n&&count(exist.begin(),exist.end(),1)==k) { v1.clear(); for(int i=0;i<n;i++) { if(exist[i]==1) v1.push_back(i+1); } v.push_back(v1); //return; } } };
参考代码
class Solution { private: vector<vector<int> > ret; vector<int> a; public: void solve(int dep, int maxDep, int n, int start) { if (dep == maxDep) { ret.push_back(a); return; } for(int i = start; i <= n; i++) { a[dep] = i; solve(dep + 1, maxDep, n, i + 1); } } vector<vector<int> > combine(int n, int k) { a.resize(k); ret.clear(); solve(0, k, n, 1); return ret; } };