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],
]
Solution
递归回溯,每次对目标的第Index位进行填数,因为求的是排列组合而不是全排列,所以每次只要填比之前更大的数就好,所以用“start”来记录当前填到了哪个数字。加了一个优化来提前终止不可能的尝试(比如剩下的数字不够填满剩下的空位),69 ms AC,速度挺快,排到了前10%。
Code
class Solution {
public:
void dfs(int Index, int start, int n, int k, vector<int> &temp, vector<vector<int> > &res)//填temp的第Index位,候选数字从start开始
{
if(Index == k+1)
{
res.push_back(temp);
temp.pop_back();
return;
}
for(int i=start;i<=n;i++)
{
if(n-start+1 < k-Index+1)//剩下的数字不够填了
break;
vector<int> tt = temp;
temp.push_back(i);
dfs(Index+1, i+1, n, k, temp, res);
temp = tt;
}
}
vector<vector<int>> combine(int n, int k)
{
vector<vector<int> > res;
vector<int> temp;
dfs(1, 1, n, k, temp, res);
return res;
}
};