We can observe that there are many subproblems being solved again and again so the problem can be solved using Dynamic Programming (DP). We can easily make memoization solution to this problem.

Time complexity : O(a*b*c)Auxiliary Space : O(a*b*c*3)

// table to store to store results of subproblems

intdp[MAX][MAX][MAX][3];

// Returns count of arrangements where last placed ball is

// 'last'. 'last' is 0 for 'a', 1 for 'b' and 2 for 'c'

intcountWays(inta, intb, intc, intlast)

{

// if number of balls of any color becomes less

// than 0 the number of ways arrangements is 0.

if(a<0 || b<0 || c<0)

return0;

// If last ball required is of type A and the number

// of balls of A type is 1 while number of balls of

// other color is 0 the number of ways is 1.

if(a==1 && b==0 && c==0 && last==0)

return1;

// Same case as above for 'b' and 'c'

if(a==0 && b==1 && c==0 && last==1)

return1;

if(a==0 && b==0 && c==1 && last==2)

return1;

// If this subproblem is already evaluated

if(dp[a][b][last] != -1)

returndp[a][b][last];

// if last ball required is A and the number of ways is

// the sum of number of ways to form sequence with 'a-1' A

// balls, b B Balls and c C balls ending with B and C.

if(last==0)

dp[a][b]1[last] = countWays(a-1,b,c,1) + countWays(a-1,b,c,2);

// Same as above case for 'b' and 'c'

elseif(last==1)

dp[a][b]1[last] = countWays(a,b-1,c,0) + countWays(a,b-1,c,2);

else//(last==2)

dp[a][b]1[last] = countWays(a,b,c-1,0) + countWays(a,b,c-1,1);

returndp[a][b]1[last];

}

// Returns count of required arrangements

intcountUtil(inta, intb, intc)

{

// Initialize 'dp' array

memset(dp, -1, sizeof(dp));

// Three cases arise:

returncountWays(a, b, c, 0) + // Last required balls is type A

countWays(a, b, c, 1) + // Last required balls is type B

countWays(a, b, c, 2); // Last required balls is type C

}

The naive solution to this problem is a recursive solution. We recursively call for three cases1) Last ball to be placed is of type A2) Last ball to be placed is of type B3) Last ball to be placed is of type C