使用 C++ 查詢配對人員的方法數


為了解決一個問題,其中 n - 人數,現在每個人可以是單身或成對出現,所以我們需要找到這些人員配對的總方法數。

Input : 3

Output: 4

Explanation : [ {1}, {2}, {3},], [{1, 2}, {3}], [{1}, {2, 3}], [{1, 3}, {2}] these four ways are the only ways we can pa up these 3 people.

Input : 6

Output : 76

解決方法

在這種方法中,我們將使用**楊氏圖表**公式來計算這個問題,我們將使用的公式是 -

A[n] = A[n-1] + (n-1) * A[n-2]

示例

上述方法的 C++ 程式碼

#include <bits/stdc++.h>
using namespace std;
int Young_Tableau(int n){
    int A[n + 1];// To store the answer.
    A[1] = 1; // initial values
    A[2] = 2; // initial values
    for (int i = 3; i <= n; i++) { // using the formula of "Young Tableau" to calculate our answer
        A[i] = A[i - 1] + (i - 1) * A[i - 2];
    }
    return A[n]; // returning the answer
}
int main(){
    int n = 6;
    cout << Young_Tableau(n);
    return 0;
}

輸出

76

上述程式碼的解釋

**在上述方法中,我們簡單地應用了楊氏圖表的公式,其中我們需要找到**前兩個數字。現在我們可以將這些數字儲存在陣列索引中。透過訂閱,我們可以獲得公式的值,從而計算出答案。

結論

在本教程中,我們解決了一個問題,即查詢配對人員的多種方法。我們還學習了此問題的 C++ 程式以及我們解決此問題的完整方法(常規)。我們可以在其他語言(如 C、Java、Python 等)中編寫相同的程式。希望本教程對您有所幫助。

更新於: 2021年11月25日

238 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告