[leetcode] Combinations

Combinations

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],
]
 1 class Solution
 2 {
 3 public:
 4   void Combination(vector<vector<int> > &ret, vector<int> &temp, int n, int k, int pos)
 5   {
 6     if(temp.size() == k)
 7     {
 8       ret.push_back(temp);
 9       return;
10     }
11 
12     while(temp.size() <= k && pos <= n)
13     {
14       temp.push_back(pos);
15       Combination(ret, temp, n, k, pos+1);
16       temp.pop_back();
17       pos++;
18     }
19   }
20   vector<vector<int> > combine(int n, int k)
21   {
22     vector<vector<int> > ret;
23     vector<int> temp;
24 
25     Combination(ret, temp, n, k, 1);
26 
27     return ret;
28   }
29 };

原文地址:https://www.cnblogs.com/lxd2502/p/4344985.html