C++组合数学:从n个元素中选取r个,其中k个元素必须在一起
给定n、r、k,我们需要找到从n个元素中选择r个元素的方法数,其中特定k个元素必须始终在一起。
Input : n = 8, r = 5, k = 2 Output : 960 Input : n = 6, r = 2, k = 2 Output : 2
这个问题需要一些组合数学知识,因为它要求我们找到n和r的排列组合,其中k个元素必须在一起。
解决方法
我们需要为这个问题制定一个公式,这将给我们答案。
示例
#include <bits/stdc++.h>
using namespace std;
int fact(int n){ // function to calculate factorial of a number
if(n <= 1)
return 1;
return n * fact(n-1);
}
int npr(int n, int r){ // finding permutation
int pnr = fact(n) / fact(n - r);
return pnr;
}
int countPermutations(int n, int r, int k){ // the formula that we came up with
return fact(k) * (r - k + 1) * npr(n - k, r - k);
}
int main(){
int n = 8;
int r = 5;
int k = 2;
cout << countPermutations(n, r, k);
return 0;
}输出
960
以上代码的解释
在上述方法中,我们尝试设计一个公式来计算答案。对于这个问题,我们设计的公式是 (k!) * (r - k + 1) * P(n-k, r-k)。(P(x, y) 是从x个元素中选择y个元素的排列数),因此我们建立了公式并计算答案。
结论
在本教程中,我们解决了一个问题,即如何求解从n个元素中选取r个,其中k个元素必须在一起的排列组合。我们还学习了这个问题的C++程序和完整的解决方法。
我们可以使用其他语言(例如C、Java、Python等)编写相同的程序。希望本教程对您有所帮助。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP