典型的DFS求所有满足条件的解。分析样例,从[1,2,3,4]中选2个数组合,[2,4],[4,2]是相同的,我们手算的过程应该是拿出1与后面[2,3,4]依次组合,2与[3,4]依次组合,3与4组合,4后面没有数了,结束。可以立刻画出搜索过程的示意图:
利用start变量,每一层[start,n]遍历,很容易实现手算的过程
转化为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>> combine(int n, int k) {
// write your code here
vector<vector<int>> res;
vector<int> tmp;
getResult(res,n,k,1,tmp);
return res;
}
void getResult(vector<vector<int>>& res,int n,int k,int start,vector<int> tmp){
if(tmp.size()==k){
res.push_back(tmp);
return;
}
//从当前层数开始
for(int i=start;i<=n;++i){
tmp.push_back(i);
getResult(res,n,k,i+1,tmp);
tmp.pop_back();
}
}
};
关于结果顺序的一个细节问题:按照程序的搜索过程,先用1与后面的组合,结果应该是[1,2],[1,3],[1,4]....与题目中样例的顺序不同,实际上这里不要求结果按照样例的顺序,后面许多题目,如括号匹配等等都是这样