LeetCode 77. 组合
我自己是通过深度优先搜索实现的,虽然效率不高但是思路很简单
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int> > v;
DFS(1,v,n,k);
return v;
}
private:
vector<int> temp;
void DFS(int index,vector<vector<int> > &v,int n, int k){
if(temp.size()==k){
v.push_back(temp);
return;
}
if(index>n||temp.size()>k) return;
temp.push_back(index);
DFS(index+1,v,n,k);
temp.pop_back();
DFS(index+1,v,n,k);
}
官方提供了一个字典序的方法
class Solution {
public:
vector<int> temp;
vector<vector<int>> ans;
vector<vector<int>> combine(int n, int k) {
// 初始化
// 将 temp 中 [0, k - 1] 每个位置 i 设置为 i + 1,即 [0, k - 1] 存 [1, k]
// 末尾加一位 n + 1 作为哨兵
for (int i = 1; i <= k; ++i) {
temp.push_back(i);
}
temp.push_back(n + 1);
int j = 0;
while (j < k) {
ans.emplace_back(temp.begin(), temp.begin() + k);
j = 0;
// 寻找第一个 temp[j] + 1 != temp[j + 1] 的位置 t
// 我们需要把 [0, t - 1] 区间内的每个位置重置成 [1, t]
while (j < k && temp[j] + 1 == temp[j + 1]) {
temp[j] = j + 1;
++j;
}
// j 是第一个 temp[j] + 1 != temp[j + 1] 的位置
++temp[j];
}
return ans;
}
};
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/combinations/solution/zu-he-by-leetcode-solution/
来源:力扣(LeetCode)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步