Suppose we have 2 balls of type ‘A’, 1 ball of type ‘B’ and 1 ball of type ‘C’, following are the ways to arrange them in the required fashion.
ABCA
ABAC
ACBA
ACAB
BACA
CABA
Hence, there is a total of six ways.
The first line of input contains an integer ‘T’ denoting the number of test cases.
The first line of each test contains three space-separated positive integers a, b, c, denoting the number of balls of type ‘A’, ‘B’, and ‘C’ respectively.
For each test case, print the total ways to arrange the balls such that adjacent balls are of a different type in a single line.
Print the output of each test case in a separate line.
You don’t have to print anything, it has already been taken care of. Just complete the function.
If there is no way, return 0.
1 <= T <= 100
0 <= a, b, c <= 15
Time limit: 1 sec
This problem can be solved by solving its subproblems and then combining the solutions of the solved subproblems to solve the original problem. We will do this using recursion. We will keep track of the next ball we want to add in the line. Initially, we have three options, to begin with. We can start by adding A or B or C. After that, at each step, we have two options. We can find the number of ways to make the required arrangements from the remaining balls.
In the recursive approach, there are many overlapping sub-problems. This problem can be solved using memoization.
Algorithm
The idea is to use Dynamic Programming.
We will create a 4D lookup table, DP, to store the solutions to the subproblems where DP[i][j][k][l] denotes the number of ways to arrange the ‘i’ balls of type A,’j’ balls of type B and ‘k’ balls of type C in the required fashion when the next ball we need to add in the line will be known from the value of ‘l’, that is when ‘l’ is 0, we need to place a ball of type ‘A’ and when ‘l’ is 1, we need to place a ball of type B and when ‘l’ is 2, we need to place a ball of type C.
Note that ‘l’ can only attain three values, 0, 1, and 2.
Algorithm