
给定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 的排列数),因此我们提出公式,并计算答案。
结论
在本教程中,我们解决一个问题,找到一次将 r 个事物与 k 个事物放在一起的排列。我们还学习了该问题的C++程序以及解决该问题的完整方法(Normal)。
我们可以用其他语言编写相同的程序,例如C、java、python等语言。我们希望本教程对您有所帮助。

