|
| 1 | +# 1220. Count Vowels Permutation |
| 2 | + |
| 3 | +- Difficulty: Hard. |
| 4 | +- Related Topics: Dynamic Programming. |
| 5 | +- Similar Questions: . |
| 6 | + |
| 7 | +## Problem |
| 8 | + |
| 9 | +Given an integer `n`, your task is to count how many strings of length `n` can be formed under the following rules: |
| 10 | + |
| 11 | + |
| 12 | + |
| 13 | +- Each character is a lower case vowel (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) |
| 14 | + |
| 15 | +- Each vowel `'a'` may only be followed by an `'e'`. |
| 16 | + |
| 17 | +- Each vowel `'e'` may only be followed by an `'a'` or an `'i'`. |
| 18 | + |
| 19 | +- Each vowel `'i'` **may not** be followed by another `'i'`. |
| 20 | + |
| 21 | +- Each vowel `'o'` may only be followed by an `'i'` or a `'u'`. |
| 22 | + |
| 23 | +- Each vowel `'u'` may only be followed by an `'a'.` |
| 24 | + |
| 25 | + |
| 26 | +Since the answer may be too large, return it modulo `10^9 + 7.` |
| 27 | + |
| 28 | + |
| 29 | +Example 1: |
| 30 | + |
| 31 | +``` |
| 32 | +Input: n = 1 |
| 33 | +Output: 5 |
| 34 | +Explanation: All possible strings are: "a", "e", "i" , "o" and "u". |
| 35 | +``` |
| 36 | + |
| 37 | +Example 2: |
| 38 | + |
| 39 | +``` |
| 40 | +Input: n = 2 |
| 41 | +Output: 10 |
| 42 | +Explanation: All possible strings are: "ae", "ea", "ei", "ia", "ie", "io", "iu", "oi", "ou" and "ua". |
| 43 | +``` |
| 44 | + |
| 45 | +Example 3: |
| 46 | + |
| 47 | +``` |
| 48 | +Input: n = 5 |
| 49 | +Output: 68 |
| 50 | +``` |
| 51 | + |
| 52 | + |
| 53 | +**Constraints:** |
| 54 | + |
| 55 | + |
| 56 | + |
| 57 | +- `1 <= n <= 2 * 10^4` |
| 58 | + |
| 59 | + |
| 60 | + |
| 61 | +## Solution |
| 62 | + |
| 63 | +```javascript |
| 64 | +/** |
| 65 | + * @param {number} n |
| 66 | + * @return {number} |
| 67 | + */ |
| 68 | +var countVowelPermutation = function(n) { |
| 69 | + var dp = Array(n).fill(0).map(() => ({})); |
| 70 | + return helper('', n, dp); |
| 71 | +}; |
| 72 | + |
| 73 | +var helper = function(lastChar, n, dp) { |
| 74 | + if (n === 0) return 1; |
| 75 | + if (dp[n - 1][lastChar] !== undefined) return dp[n - 1][lastChar]; |
| 76 | + var mod = Math.pow(10, 9) + 7; |
| 77 | + var res = 0; |
| 78 | + if (!lastChar || lastChar === 'e') res = (res + helper('a', n - 1, dp)) % mod; |
| 79 | + if (!lastChar || lastChar === 'a' || lastChar === 'i') res = (res + helper('e', n - 1, dp)) % mod; |
| 80 | + if (!lastChar || lastChar !== 'i') res = (res + helper('i', n - 1, dp)) % mod; |
| 81 | + if (!lastChar || lastChar === 'i' || lastChar === 'u') res = (res + helper('o', n - 1, dp)) % mod; |
| 82 | + if (!lastChar || lastChar === 'a') res = (res + helper('u', n - 1, dp)) % mod; |
| 83 | + dp[n - 1][lastChar] = res; |
| 84 | + return res; |
| 85 | +}; |
| 86 | +``` |
| 87 | + |
| 88 | +**Explain:** |
| 89 | + |
| 90 | +nope. |
| 91 | + |
| 92 | +**Complexity:** |
| 93 | + |
| 94 | +* Time complexity : O(n). |
| 95 | +* Space complexity : O(n). |
0 commit comments