### wish_me's blog

By wish_me, history, 2 years ago, ,

Given 3 characters a, b, c, find the number of strings of length n that can be formed from these 3 characters given that; we can use ‘a’ as many times as we want, ‘b’ maximum once, and ‘c’ maximum twice

• -10

 » 2 years ago, # |   0 Can you describe what is your approach to solve this problem?
•  » » 2 years ago, # ^ |   0 I tried to solve it recursivly by generating all possible strings and then discarding those strings which doesn't follow above rule?Can you tell me more efficient approach?
•  » » » 2 years ago, # ^ | ← Rev. 2 →   0 How about using permutaions? Number of strings containing only a's. Number of strings containing 1 b and rest a's. Number of strings containing 1c and rest a's. . . .and add the sum of all the above points to get the final answer.
•  » » » » 2 years ago, # ^ |   0 Suppose IF we need to print the strings then?
•  » » » » 2 years ago, # ^ |   0 then how to print them in minimum complexity?
•  » » » » » 2 years ago, # ^ | ← Rev. 2 →   0 The best you can do is where M is the number of possibilities. To do it efficiently, make some string of length n, and recursively fix the character. You'd do this from left to right, and your recursive function should pass down information on whether or not you've fixed the letter b, and how many c's you've fixed so far.
•  » » » » » » 2 years ago, # ^ |   0 thanks a lot sir.Can you write pseudo code?
•  » » » » » » » 2 years ago, # ^ | ← Rev. 2 →   0 Not too hard: s = std::string(n, ' '); def rec(i, bs, cs): if i == n: print s else: s[i] = a rec(i+1, bs, cs) if bs < 1: s[i] = b rec(i+1, bs+1, cs) if cs < 2: s[i] = c rec(i+1, bs, cs+1) rec(0, 0, 0) 
•  » » » » » » » » 2 years ago, # ^ |   0 thnx sir
 » 2 years ago, # |   0 I assume you're solving this, since N<=20 you can use: Spoilerint n; cin>>n; cout<<1+2*n+3*cnk(2,n)+3*cnk(3,n)<
•  » » 2 years ago, # ^ |   0 thnx sir
 » 2 years ago, # | ← Rev. 2 →   0 There aren't many possible cases if we care only about 'b' and 'c'. Let's focus only on placing 'b' and 'c', the remaining will be 'a':1) no 'b' and 'c': 1 option.2) only 1 'b': n options.3) only 1 'c': n options.4) 2 'c': n(n — 1) / 2 options.5) 1 'b' and 1 'c': n(n — 1) options.6) 1 'b' and 2 'c': n(n — 1)(n — 2) / 6 * 3 = n(n — 1)(n — 2) / 2 options.so to sum it up, given n you need to output: 1 + 2n + 3n(n — 1) / 2 + n(n — 1)(n — 2) / 2.this is O(1) which means it's slightly faster than an exponential complexity by using recursion.
•  » » 5 months ago, # ^ |   +7 Yes, constant time is indeed slightly faster than exponential time.
 » 20 months ago, # |   0 here is the code i wrote in C language for this problem if there are some suggestions , i am open to them ;)https://www.ideone.com/GWm4T3
 » 5 months ago, # |   -19 def permute(n,s): if len(s)>n: return if len(s)==n: if s.count("b")<=1 and s.count("c")<=2: l.append(s) return for i in ("a","b","c"): permute(n,s+i) n=3 s="" l=[] permute(n,s) print(len(l),l)