题目
Number: 77
Difficulty: Medium
Tags: Backtracking
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],
]
题解
给出两个整数k和n,在1...n
中找出所有k个数的组合。
用回溯法求解。
代码
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> res;
if(n < k) return res;
vector<int> ans;
com(res, ans, n, k, 0);
return res;
}
void com(vector<vector<int>> &res, vector<int> &ans, int n, int k, int start) {
if(ans.size() == k){
res.push_back(ans);
return;
}
for(int i = start; i < n; i++){
ans.push_back(i + 1);
com(res, ans, n, k, i + 1);
ans.pop_back();
}
}