组合数
作者:
zplzh
,
2024-04-13 20:56:58
,
所有人可见
,
阅读 3
#include <iostream>
#include <vector>
using namespace std;
// 计算阶乘
int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
// 计算组合数方案数
int combination(int n, int k) {
int numerator = factorial(n);
int denominator = factorial(k) * factorial(n - k);
return numerator / denominator;
}
// 输出每一个组合方案
void printCombination(vector<int>& combination) {
for (int num : combination) {
cout << num << " ";
}
cout << endl;
}
// 递归生成组合方案
void generateCombination(vector<int>& nums, vector<int>& combination, int start, int k) {
if (k == 0) {
printCombination(combination);
return;
}
for (int i = start; i < nums.size(); i++) {
combination.push_back(nums[i]);
generateCombination(nums, combination, i + 1, k - 1);
combination.pop_back();
}
}
// 求解组合数方案数并输出每一个方案
void solveCombination(int n, int k) {
vector<int> nums;
for (int i = 1; i <= n; i++) {
nums.push_back(i);
}
vector<int> combination;
generateCombination(nums, combination, 0, k);
}
int main() {
int n, k;
cout << "请输入总数n和选择的个数k:" << endl;
cin >> n >> k;
int result = combination(n, k);
cout << "组合数方案数为:" << result << endl;
cout << "每一个组合方案为:" << endl;
solveCombination(n, k);
return 0;
}