[LeetCode] 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],
]


简单的组合问题,用类似dfs的方法
 1 class Solution {
 2 private:
 3     vector<vector<int> > ret;
 4     vector<int> a;
 5 public:
 6     void solve(int dep, int maxDep, int n, int start)
 7     {
 8         if (dep == maxDep)
 9         {
10             ret.push_back(a);
11             return;
12         }
13         
14         for(int i = start; i <= n; i++)
15         {
16             a[dep] = i;
17             solve(dep + 1, maxDep, n, i + 1);
18         }      
19     }
20     
21     vector<vector<int> > combine(int n, int k) {
22         // Start typing your C/C++ solution below
23         // DO NOT write int main() function
24         a.resize(k);
25         ret.clear();
26         solve(0, k, n, 1);
27         return ret;
28     }
29 };
原文地址:https://www.cnblogs.com/chkkch/p/2744722.html