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], ]
思路:很简单的递归问题。
vector<vector<int> > combine(int n, int k) { int pos = 1; vector<int> comb; vector<vector<int>> combs; combineUtil(n, k, pos, comb, combs ); return combs; } void combineUtil(int n, int k, int pos, vector<int> comb, vector<vector<int>>& combs ) { // n: 1,2,..., n // k: select k numbers from [1,n] // pos: the number from [1,n] that may be selected. // This is the depth of the state stack. // comb: the selected numbers will be stored in comb. // combs: a completed combination will be stored in combs. if(comb.size()==k) { combs.push_back(comb); return; } if( n-pos+1<k-comb.size() ) return; comb.push_back(pos); pos++; combineUtil(n, k, pos, comb, combs ); comb.pop_back(); combineUtil(n, k, pos, comb, combs ); }