好友結對問題
在一個組中,有 n 個朋友。每個人可以選擇保持單身或與其他朋友配對。求解朋友保持單身或配對的所有方法數。
如果一對朋友是 p 和 q,則 (p,q) 或 (q,p) 相同。
對於一個 n 人組,設 f(n) 為他們可以配對或保持單身的方案數。那麼,第 n 個人要麼保持單身,要麼配對。如果第 n 個人單身,那麼我們對 (n - 1) 個朋友進行遞迴。如果第 n 個人與剩下的 (n-1) 個朋友中任意一個人配對,那麼我們進行遞迴 (n-1) *f(n-2)。
輸入和輸出
Input: The number of friends. Say 5. Output: The possible way to pair them. Here the answer is 26.
演算法
countPairs(n)
輸入:朋友人數。
輸出:配對 n 個朋友的方法數。
Begin define pair array of size n + 1 pair[0] := 0, pair[1] := 1 and pair[2] := 2 for i in range 3 to n, do pair[i] := pair[i-1] + (i+1)*pairs[i-2] done pair[n] End
示例
#include <iostream> using namespace std; int countPairs(int n) { int pairs[n + 1]; //number of pairs for ith number //for number 0 to 2, there are 0 to 2 possible combination pairs[0] = 0; pairs[1] = 1; pairs[2] = 2; for (int i = 3; i <= n; i++) //fill array for 3 to n numbers pairs[i] = pairs[i-1] + (i-1) * pairs[i-2]; return pairs[n]; } int main() { int n; cout << "Enter numbers: "; cin >> n; cout << "Number of ways to pair "<<n<<" friends: " << countPairs(n); }
輸出
Enter numbers: 5 Number of ways to pair 5 friends: 26
廣告