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
№ | Пользователь | Рейтинг |
---|---|---|
1 | tourist | 4009 |
2 | jiangly | 3823 |
3 | Benq | 3738 |
4 | Radewoosh | 3633 |
5 | jqdai0815 | 3620 |
6 | orzdevinwang | 3529 |
7 | ecnerwala | 3446 |
8 | Um_nik | 3396 |
9 | ksun48 | 3390 |
10 | gamegame | 3386 |
Страны | Города | Организации | Всё → |
№ | Пользователь | Вклад |
---|---|---|
1 | cry | 165 |
2 | maomao90 | 164 |
3 | Um_nik | 163 |
4 | atcoder_official | 160 |
4 | adamant | 160 |
6 | -is-this-fft- | 158 |
7 | awoo | 157 |
8 | TheScrasse | 154 |
9 | nor | 153 |
9 | Dominater069 | 153 |
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
Название |
---|
Can you describe what is your approach to solve this problem?
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?
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.
then how to print them in minimum complexity?
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 manyc
's you've fixed so far.thanks a lot sir.Can you write pseudo code?
Not too hard:
I assume you're solving this, since N<=20 you can use:
(cnk = number of combinations)
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.
Yes, constant time is indeed slightly faster than exponential time.