LeetCode OJ: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 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 };
java版本的如下所示,去除了所有的全局变量,看起来简洁一点:
1 public class Solution { 2 public List<List<Integer>> combine(int n, int k) { 3 List<List<Integer>> ret = new ArrayList<List<Integer>>(); 4 List<Integer> tmp = new ArrayList<Integer>(); 5 dfs(ret, tmp, 1, n, k); 6 return ret; 7 } 8 9 public void dfs(List<List<Integer>> ret, List<Integer> tmp, int start, int n, int k) 10 { 11 if(tmp.size() == k){ 12 List<Integer> list = new ArrayList<Integer>(tmp); 13 ret.add(list); 14 return; 15 } 16 for(int i = start; i <= n; ++i){ 17 tmp.add(i); 18 dfs(ret, tmp, i + 1, n, k); 19 tmp.remove(new Integer(i)); //这里比较重要 20 } 21 } 22 }