Блог пользователя wish_me

Автор wish_me, история, 9 лет назад, По-английски

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
  • Проголосовать: не нравится

»
9 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Can you describe what is your approach to solve this problem?

»
9 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

I assume you're solving this, since N<=20 you can use:

Spoiler
»
9 лет назад, скрыть # |
← 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.