http://oj.leetcode.com/problems/combinations/
class Solution {
private:
vector<bool> used;
vector<vector<int> > res;
vector<int> current;
public:
// It asks for all the combinations, so we need the variable last to avoid duplications
void DFS(int n, int k, int depth, int last=-1){
if(depth==k){
res.push_back(current);
}
else{
for(int i=last+1;i<n;i++){
if(used[i]==false){
current[depth]=i+1;
used[i]=true;
DFS(n, k, depth+1, i);
used[i]=false;
}
}
}
}
vector<vector<int> > combine(int n, int k) {
used.clear();
res.clear();
current.clear();
if(k==0) return res;
for(int i=0;i<n;i++) used.push_back(false);
for(int i=0;i<k;i++) current.push_back(0);
DFS(n, k, 0);
return res;
}
};
本文详细介绍了如何使用深度优先搜索解决LeetCode上的组合问题。通过实例解析,读者将学会如何生成指定数量的组合,理解回溯算法在组合问题中的应用。
1194

被折叠的 条评论
为什么被折叠?



