标签:
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
For example,
If n = 4 and k = 2, a solution is:
[ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
class Solution { public: vector<vector<int>> res; vector<int> part; void com(int dep,int maxdep,int n,int start) { if(dep==maxdep) { res.push_back(part); return; } for(int i=start;i<=n;i++) { part[dep]=i; com(dep+1,maxdep,n,i+1); } } vector<vector<int>> combine(int n, int k) { if(n<1) return res; part.resize(k); if(k==0||k==n) { part.resize(n); for(int i=1;i<=n;i++) part[i-1]=i; res.push_back(part); return res; } com(0,k,n,1); return res; } };
class Solution { public: int int_to_bool(int n,vector<int>&index)//返回1出现的次数,也就是组合中元素的个数 { int len=index.size(); index.clear(); index.resize(len); int i=0; int add=0; while(n) { int temp=n%2; index[i]=temp; if(temp==1) add++; i++; n/=2; } return add; } vector<vector<int>> combine(int n, int k) { vector<vector<int>> res; if(n<1) return res; vector<int> num; for(int i=1;i<=n;i++) num.push_back(i); if(k==0||k==n) { res.push_back(num); return res; } vector<int> index(n,0); for(int i=0;i<(1<<n);i++) { if(int_to_bool(i,index)==k) { vector<int> temp; for(int j=0;j<n;j++) { if(index[j]==1) temp.push_back(num[j]); } res.push_back(temp); } } return res; } };
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/sinat_24520925/article/details/46835569