


The answer could be very large, output answer %(10 ^ 9 + 7).
The first line of input contains an integer ‘T’ denoting the number of test cases.
The first line and the only line of each test case contains an integer ‘N’ denoting the number of elements whose derangements are to be counted.
For each test case, return the total number of derangements of a set of ‘N’ elements.
You don't need to print anything, it has been already taken care of. Just implement the given function.
1 <= T <= 100
1 <= N <= 3000
Time limit: 1 sec
Let’s understand this approach with an example.
Consider ‘N’ = 4, the elements will be {0, 1, 2 ,3}.
Below is the recursive relation for it.
countDerangement(n) = ('N' - 1) * [countDerangement('N' - 1) + countDerangement('N' - 2)]
How does the above recursive relation work?
An element can be placed at any index other than its original index and the indexes where previous elements are placed, that means, there are 'N' - 1 possible positions, which explains multiplication by ('N' - 1).
There are two possibilities:
The steps are as follows:
countDerangement('N')=('N' - 1) * [countDerangement('N' - 1)+countDerangement('N' - 2)].
We can observe that this implementation, recalculates various problems. So, to avoid this, the idea is to store the results of subproblems in an array and build the array in a bottom-up manner.
The steps are as follows:
The steps are as follows: