


1. Return the final answer by doing a mod with 10^9 + 7.
2. Pairs {A, B} and {B, A} are considered the same.
The first line of input contains an integer ‘T’, denoting the number of test cases. The test cases follow.
The first line of each test case contains one integer, ‘N’, denoting the number of friends.
For each test case, return the total number of ways in which the pairing can be done.
1<= T <= 100
1 <= N <= 10^4
Time Limit: 1 sec
The idea is to solve the problem using recursion and break down the problem into different subproblems.
Let’s define NUMBER_OF_WAYS(N) as the total number of ways ‘N’ friends can be paired up or remain single.
The N-th person has two choices - either remain single or pair up with one of the other ‘N - 1’ friends.
If he remains single, then the number of possible pairings are NUMBER_OF_WAYS(N - 1) as there are (N - 1) more friends to be paired up or stay single.
If he pairs up, he can pair with any one of the (N - 1) friends, and there are (N - 2) friends to be paired up or remain single. Hence, by the rule of product, the number of possible pairings, in this case, will be (N-1)*NUMBER_OF_WAYS(N-2).
So, the recurrence relation can be written as :
On observing the recursion tree for the previous problem, we can see that we are solving a subproblem multiple times, i.e., for some ‘X’ we are calculating the value of NO_OF_WAYS(X) multiple times.
The idea here is similar to the previous approach. But in this approach, we will be avoiding repeated recursion calls for a subproblem by storing the results for the subproblems.
The idea is to store the answer of the current recursive call in an array and then return the answer.
This approach is called Memoization.
The steps are as follows:
The idea here is to solve the problem iteratively and store the results in an array.
This approach is called Tabulation. In this approach, we compute all the answers starting from ‘i’ = 1 to 'N’, i.e., we check the total number of ways we can pair if 'N’ = 1, then 'N' = 2,......'N' = 'N'.
Here, we can observe that calculating for the current subproblem,NO_OF_WAYS (N), only the last answer, i.e., NO_OF_WAYS(N-1), and the second last answer, i.e., NO_OF_WAYS(N-2), is used.
We can also use two variables to store both the answers.