![]() |
VOOZH | about |
Given a length n, count the number of strings of length n that can be made using 'a', 'b' and 'c' with at most one 'b' and two 'c's allowed.
Examples :
Input: n = 3
Output: 19
Explanation:
Number of strings with 3 occurrances of a: 1
2-a and 1-b: 3
2-a and 1-c: 3
1-a, 1-b and 1-c: 6
1-a and 2-c: 3
1-b and 2-c: 3
So, total number of strings of length 3
is 1 + 3 + 3 + 6 + 3 + 3 = 19Input: n = 1
Output: 3
Explanation: Possible strings are: "a", "b" and "c"
Table of Content
A simple solution is to recursively build strings by choosing
'a','b', or'c'at each step while keeping track of remaining allowed counts of'b'and'c'.
19
Use recursion with a DP array to store already computed states
(n, bCount, cCount)and reuse them to avoid repeated calculations.
19
The idea is to use the formula that the number of ways we can arrange a total of n objects, out of which p number of objects are of one type, q objects are of another type, and r objects are of the third type is n ! /( p! q! r!)
The answer is 1 because we can arrange a string consisting of only 'a' in one way only and the string would be aaaa....(n times).
The answer is n because we can arrange a string consisting (n-1) 'a's and 1 'b' is n! / (n - 1)! = n. The same goes for 'c' .
Answer is n * (n - 1) + n * (n - 1)/2 . Because that 2 places can be either 1 'b' and 1 'c' or 2 'c' according to our given constraints. For the first case, total number of arrangements is n! /(n - 2)! = n * (n - 1) and for second case that is n! / (2!(n - 2)! ) = n * (n - 1)/2 .
Answer is (n - 2)*(n - 1)*n /2 . Because those 3 places can only be consisting of 1 'b' and 2'c' according to our given constraints. So, total number of arrangements is n! /(2! (n - 3)!) = (n - 2) * (n - 1) * n/2 .
19