If the ‘N’ is 3. The number of ways will be 2 shown below:
The first line of the input contains an integer, 'T,’ denoting the number of test cases.
The first line of each test case contains a single integer, ‘N’, denoting the length of the box.
For each test case, print the number of ways.
Print the output of each test case in a separate line.
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 100000.
Time limit: 1 sec
Intution: Lets denote U[n] is the number of ways to fill the box of size 3*N using the dominos.
and V[n] is defined as the number ways to fill the 3*n rectangle box without a lower left corner.
U[n] can be break into smaller subproblems as U[n-2] + V[n-1] + V[n-1] shown in the figure below.
V[n] can be similarly break into smaller subproblems as V[n-2] +U[n-1] shown in the figure below.
So, using these all relations ,the final recursive realtion is U[n] = U[n-2] + 2*V[n-1] and V[n] = U[n-1] + V[n-2].
Base Cases will be :
So, using these equations we will define two functions findU(n) that will return the value of U[n] and findV(n) that will return the value of V[n] as described above.At last,we will return the value of findU(n) corresponding to the final answer.
In approach 1, we used recursive approach to calculate the answer.
In this approach, we will use the same recursive function and will memoize the solution to reduce the time complexity.
So, using these equations we will define two functions findU(n) that will return the value of U[n] and findV(n) that will return the value of V[n] as described in Approach 1 and store the values in U[n] and V[n] respectively. At last, we will return the value of findU(n) corresponding to the final answer.
As we discussed the relations in approach 1, we will declare two arrays U and V to store the values corresponding to U[i] and V[i] in these arrays. So first we will set the base case values and then we will iterate from 3 to N and find the values of U[i] and V[i] using the equations and at last, we will return U[N] as the final answer.