题目链接:
https://leetcode-cn.com/problems/combinations/
难度:中等
77. 组合
给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
示例:
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
Not difficult
or recursively convenient. . .
class Solution {
public:
vector<vector<int>> ans;
vector<int> curvec;
vector<vector<int>> combine(int n, int k) {
dfs(1,n,k);
return ans;
}
void dfs(int cursize,int n,int k){
if(curvec.size()==k){
ans.push_back(curvec);
return;
}
if(curvec.size()+n-cursize+1<k){
return;
}
curvec.push_back(cursize);
dfs(cursize+1,n,k);
curvec.pop_back();
dfs(cursize+1,n,k);
}
};
Recursion is indeed simple and another method is really unexpected. . . Record coordinate explanations
barely understand estimate the next time forgot
原序列中被选中的数 对应的二进制数 方案
4 3 [2] [1] 0011 2, 1
4 [3] 2 [1] 0101 3, 1
4 [3] [2] 1 0110 3, 2
[4] 3 2 [1] 1001 4, 1
[4] 3 [2] 1 1010 4, 2
[4] [3] 2 1 1100 4, 3
The end is 1: such as... 0 {1 …1**}**: Exchange 0 1 (there is a string containing only 1 at the end, swap the first 1 of the string with the 0 before the 1), the
end is 0: such as... 0 {1 …1}{0…0}: Exchange 0 1 to the end of the remaining 1 method: …10{0…0}{…1} (the end is 0, there must be a string with only 0, before the 0 string There is also a string of 1, swap the first position of 1 with the previous 0, and then put the remaining 1 to the end)
{1...1}: string that only includes 1-{0...0}: only A string including 1 The
following code cleverly avoids using extra memory to save the currently selected number
(0 in the binary means not selected, 1 means to select the corresponding code. 1 means curvec[i]+1== curvec[i+1], and 0 means curvec[i]+1!=curvec[i+1])
class Solution {
public:
vector<int> curvec;
vector<vector<int>> ans;
vector<vector<int>> combine(int n, int k) {
for (int i=1;i<=k;++i) {
curvec.push_back(i);
}
// 这里必须是 n+1
curvec.push_back(n+1);
int i=0;
while(i<k){
ans.emplace_back(curvec.begin(),curvec.begin()+k);
i=0;
while(i<k&&curvec[i]+1==curvec[i+1]){
curvec[i]=i+1;
i++;
}
curvec[i]++;
}
return ans;
}
};