lintcode: Combinations
原创
©著作权归作者所有:来自51CTO博客作者mb63887cf57331d的原创作品,请联系作者获取转载授权,否则将追究法律责任
Given two integers n and k, return all possible combinations of k numbers out of 1 … n.
Example
For example,
If n = 4 and k = 2, a solution is:
[[2,4],[3,4],[2,3],[1,2],[1,3],[1,4]]
很明显就是一个DFS+回溯的问题;
跟求全排列、幂集都很像;
思路就是想象递归的搜索解决树,搜索解决数每一层的可能解。
class Solution {
public:
/**
* @param n: Given the range of numbers
* @param k: Given the numbers of combinations
* @return: All the combinations of k numbers out of 1..n
*/
vector<vector<int> > res;
void helper(int n,int k,int cur,vector<int> tmp){
if(tmp.size()==k){
res.push_back(tmp);
return;
}
//当前层有可选的数从cur到n都有可能
for(int i=cur;i<=n;i++){
tmp.push_back(i);
helper(n,k,i+1,tmp);//i+1
tmp.pop_back();
}
}
vector<vector<int> > combine(int n, int k) {
// write your code here
vector<int> tmp;
helper(n,k,1,tmp);
return res;
}
};
参考:
https://siddontang.gitbooks.io/leetcode-solution/content/backtracking/combination.html