Rencontres Number in Java
Two numbers are given to us., The first number is a whole number, denoted by n, and the second number is a nonnegative number, which is less than or equal to n, represented by k. The task is to find out the total number of disarrangements for the given numbers n and k, such that only k elements should be there at their original positions. In other words, we have to find the total number of derangements. The total
Example 1:
Input: int n = 3, int k = 0
Output: 2
Explanation: The value of k is 0. It means no number needs to be in its original position. The disarrangements are {2, 3, 1} and {3, 1, 2}.
Example 2:
Input: int n = 3, k = 1
Output: 3
Explanation: The value of k is 1. Therefore, there should be only one number that should be in its original position. Thus, the disarrangements we get are are {2, 1, 3}, {1, 3, 2}, and {3, 2, 1}.
Approach: Using Recurrence Relation In mathematics, the Rencontres numbers D(n, k) gives the total number of partial derangements. The recurrence relation is given as:
D(n, k) = ^{n}C_{k} x D(n  k, 0) and for k = 0, the relation can be given as:
D(n, 0) = (n  1) * (D(n  1, 0) + D(n  2, 0)) and for the base case, we have:
D(0, 0) = 1, D(0, 1) = 0, and D(1, 0) = 0 Thus, For n = 1, k = 1, we get D(1, 1) = ^{1}C_{1} x D(1  1, 0) = 1 x D(0, 0) = 1 x 1 = 1 For n = 2, k = 1, we get D(2, 1) = ^{2}C_{1} x D(2  1, 0) = 2 x D(1, 0) = 2 x 0 = 0 For n = 3, k = 1, we get D(3, 1) = ^{3}C_{1} x D(3  1, 0) = 3 x D(2, 0) Now, we have to find the value of D(2, 0), which can be found using the other recurrence relation. D(n, 0) = (n  1) x (D(n  1, 0) + D(n  2, 0))
D(2, 0) = (2  1) x (D(2  1, 0) + D(2  2, 0)) = 1 x (D(1, 0) + D (0, 0)) = 1 x (0 + 1) = 1 x 1 = 1
Hence, we get
D(3, 1) = 3 x D(2, 0) = 3 x 1 = 3
Now, let us implement the above relation.
FileName: RencontresNumberRec.java
Output:
For the value of n = 7 and k = 2, the total number of derangements are: 924
For the value of n = 3 and k = 1, the total number of derangements are: 3
For the value of n = 1 and k = 1, the total number of derangements are: 1
Complexity Analysis: The time complexity of the program is O(n x k), where n and k represent the input integers. The space complexity of the program is also O(n x k), because of the recursive stack.
Approach: Using Dynamic Programming
In this approach, we will first split the problems into smaller ones and then solve those smaller problems. We will store the solutions in a 2D array and then use it to find the solution to the given problem.
FileName: RencontresNumDP.java
Output:
For the value of n = 7 and k = 2, the total number of derangements are: 924
For the value of n = 3 and k = 1, the total number of derangements are: 3
For the value of n = 1 and k = 1, the total number of derangements are: 1
Complexity Analysis: The time, as well as the space complexity of the program, is the same as the previous program.
