1
+ /*
2
+ Count Vowels Permutation
3
+ ========================
4
+
5
+ Given an integer n, your task is to count how many strings of length n can be formed under the following rules:
6
+
7
+ Each character is a lower case vowel ('a', 'e', 'i', 'o', 'u')
8
+ Each vowel 'a' may only be followed by an 'e'.
9
+ Each vowel 'e' may only be followed by an 'a' or an 'i'.
10
+ Each vowel 'i' may not be followed by another 'i'.
11
+ Each vowel 'o' may only be followed by an 'i' or a 'u'.
12
+ Each vowel 'u' may only be followed by an 'a'.
13
+ Since the answer may be too large, return it modulo 10^9 + 7.
14
+
15
+ Example 1:
16
+ Input: n = 1
17
+ Output: 5
18
+ Explanation: All possible strings are: "a", "e", "i" , "o" and "u".
19
+
20
+ Example 2:
21
+ Input: n = 2
22
+ Output: 10
23
+ Explanation: All possible strings are: "ae", "ea", "ei", "ia", "ie", "io", "iu", "oi", "ou" and "ua".
24
+
25
+ Example 3:
26
+ Input: n = 5
27
+ Output: 68
28
+
29
+ Constraints:
30
+ 1 <= n <= 2 * 10^4
31
+
32
+ Hint #1
33
+ Use dynamic programming.
34
+
35
+ Hint #2
36
+ Let dp[i][j] be the number of strings of length i that ends with the j-th vowel.
37
+
38
+ Hint #3
39
+ Deduce the recurrence from the given relations between vowels.
40
+ */
41
+
42
+ class Solution
43
+ {
44
+ public:
45
+ int M = 1e9 + 7 ;
46
+
47
+ int countVowelPermutation (int n)
48
+ {
49
+ long long a = 1 , e = 1 , i = 1 , o = 1 , u = 1 ;
50
+
51
+ for (int j = 1 ; j < n; ++j)
52
+ {
53
+ long long A = 0 , E = 0 , I = 0 , O = 0 , U = 0 ;
54
+ A = e + i + u;
55
+ E = a + i;
56
+ I = e + o;
57
+ O = i;
58
+ U = i + o;
59
+
60
+ a = A % M;
61
+ e = E % M;
62
+ i = I % M;
63
+ o = O % M;
64
+ u = U % M;
65
+ }
66
+
67
+ return (a % M + e % M + i % M + o % M + u % M) % M;
68
+ }
69
+ };
0 commit comments