一.问题描述
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], ]
二.我的解题思路
拿到这道题,我的思路有两类:基于递归的算法思路和基于回溯法的算法思路。采用回溯法的程序写起来比较简单,所以我是采用的回溯法,使用子集树的结构。测试通过的程序如下:
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<int> curr;
vector<vector<int>> res;
if(n<=0) return res;
if(k>n) return res;
back_trace(res,curr,1,n,k);
return res;
}
void back_trace(vector<vector<int>> &res, vector<int> &curr, int i, int n,int k){
int curr_len=curr.size();
if(curr_len==k){
res.push_back(curr);
return;
}
if(curr_len+n-i+1<k)
return;
if(i>n) return;
curr.push_back(i);
back_trace(res,curr,i+1,n,k);
curr.pop_back();
back_trace(res,curr,i+1,n,k);
}
};