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 public: 3 vector<vector<int>> combine(int n, int k) { 4 tmp.resize(k); 5 ret.clear(); 6 dfs(0, k, n, 1); 7 return ret; 8 } 9 10 void dfs(int depth, int maxDepth, int n, int start) 11 { 12 if(depth == maxDepth){ 13 ret.push_back(tmp); 14 return; 15 } 16 for(int i = start ; i <= n; ++i){ 17 tmp[depth] = i; 18 dfs(depth + 1, maxDepth, n, i + 1); 19 } 20 } 21 private: 22 vector<vector<int>> ret; 23 vector<int> tmp; 24 };
LeetCode OJ:Combinations (排列组合)
原文:http://www.cnblogs.com/-wang-cheng/p/4889187.html