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