【正经题解】组合数的生成
2024-02-22 11:35:34
发布于:浙江
13阅读
0回复
0点赞
定义两个数组: 用来存储当前组合的数字, 用来标记数字是否已经被选择。
使用递归函数 生成组合。
在递归函数中,如果当前组合已经选择了 个数字,就输出这个组合并返回。
在每一层递归中,遍历可选的数字,如果该数字未被选择且满足当前组合的递增条件,选择这个数字,继续递归下一层。
递归完成后,取消对当前数字的选择,回溯到上一层,继续遍历其他可选的数字。
#include<bits/stdc++.h>
using namespace std;
const int MAX_N = 100;
int n, r, combination[MAX_N], visited[MAX_N];
void generateCombinations(int currentIdx){
if(currentIdx > r){
// 输出当前组合
for(int i = 1; i <= r; i++){
cout << combination[i] << " ";
}
cout << endl;
return;
}
for(int i = 1; i <= n; i++){
if(!visited[i] && (currentIdx == 1 || combination[currentIdx - 1] < i)){
visited[i] = 1;
combination[currentIdx] = i;
generateCombinations(currentIdx + 1);
visited[i] = 0;
}
}
}
int main(){
cin >> n >> r;
generateCombinations(1);
return 0;
}
这里空空如也
有帮助,赞一个