首頁  >  文章  >  後端開發  >  C++以k個元素為一組,從n個元素中取r個元素的排列

C++以k個元素為一組,從n個元素中取r個元素的排列

WBOY
WBOY轉載
2023-09-07 20:37:021007瀏覽

C++以k個元素為一組,從n個元素中取r個元素的排列

給定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等語言。我們希望本教學對您有所幫助。

以上是C++以k個元素為一組,從n個元素中取r個元素的排列的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除