Friend Pairing Problem

In a group, there is n number of friends. Each person can remain single or be paired with some other friend. Find the total number of ways, in which friends can remain single or can be paired up.

If one pair has two friends’ p and q, then (p, q) or (q, p) are same. 

For a group of n friends, let f(n) be the number of ways how they can be paired up or remain single. Then either the nth person remains single, or paired up. If the nth person is single, then we recur for (n - 1) friends. If the nth person is paired up with any of the remaining (n-1) person, then, we recur (n-1) *f(n-2).

Input and Output

The number of friends. Say 5.
The possible way to pair them. Here the answer is 26.



Input: Number of friends.

Output: Number of ways to pair n friends.

   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]



#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