77. Combinations
Given two integers n and k, return all possible combinations of k numbers out of 1 … n.
Example:
Input: n = 4, k = 2
Output:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
Approach
1.这是一道很经典的递归回溯题,返回在1~n中有k个元素的组合。写递归首先要明白两个地方,一个就是递归边界,还有就是递归式。我们这里的递归边界很明显,就是当储存的元素到达k个时候就该返回了,递归式也简单,那就是枚举pos+1~n,pos是上次递归的元素,因为不能重叠,所以需要加一。回溯在哪呢,当枚举完pos+1~n的时候,递归返回原地方时,因为vector里还装有上次的元素,所以我们要移除它,这样下次循环就不会冲突。
2.看了一下最前面的代码,跟我的几乎差不多,但我的慢一倍,原因我觉得是调用nums.size()的问题。88ms
#Code
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> st;
combination(st, vector<int>(), n, k, 1);
return st;
}
void combination(vector<vector<int>> &st, vector<int> nums, int n, int k, int pos) {
if (nums.size() == k) {
st.push_back(nums);
return;
}
for (int i = pos; i <= n; i++) {
nums.push_back(i);
combination(st, nums, n, k, i + 1);
nums.pop_back();
}
}
};