C++ 中的组合
pythonserver side programmingprogramming更新于 2025/10/25 19:56:17
假设我们有两个整数 n 和 k。我们必须从 1 ... n 中找到 k 个数字的所有可能组合。因此,如果 n = 4 且 k = 2,则组合将是 [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
为了解决这个问题,我们将遵循以下步骤 −
- 我们将使用递归函数来解决这个问题。函数solve() 接受 n、k、临时数组并开始。起始值最初为 1。其作用如下:
- 如果 temp 数组的大小 = k,则将 temp 插入 res 数组,并返回
- 对于 i := start to n,
- 将 i 插入 temp
- solve(n, k, temp, i + 1)
- 从 temp 末尾删除一个元素
- 调用 resolve 函数,如 resolve(n, k, [])
- 返回 res
示例
让我们看下面的实现,以便更好地理解 −
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<int> > v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << "[";
for(int j = 0; j <v[i].size(); j++){
cout << v[i][j] << ", ";
}
cout << "],";
}
cout << "]"<<endl;
}
class Solution {
public:
vector < vector <int> > res;
void solve(int n, int k, vector <int> temp, int start = 1){
if(temp.size() == k){
res.push_back(temp);
return;
}
for(int i = start; i <= n; i++){
temp.push_back(i);
solve(n, k, temp, i + 1);
temp.pop_back();
}
}
vector<vector<int> > combine(int n, int k) {
res.clear();
vector <int> temp;
solve(n ,k, temp);
return res;
}
};
main(){
Solution ob;
print_vector(ob.combine(5,3));
}
输入
5 3
输出
[[1,2,3],[1,2,4],[1,2,5],[1,3,4],[1,3,5],[1,4,5],[2,3,4],[2,3,5],[2,4,5],[3,4,5]]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

