[Swift]LeetCode1220. 統計元音字母序列的數目 | Count Vowels Permutation

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:爲敢(WeiGanTechnologies)
➤我的域名:https://www.zengqiang.org
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-xxnlrxlu-dq.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

Given an integer n, your task is to count how many strings of length n can be formed under the following rules:git

  • Each character is a lower case vowel ('a''e''i''o''u')
  • Each vowel 'a' may only be followed by an 'e'.
  • Each vowel 'e' may only be followed by an 'a' or an 'i'.
  • Each vowel 'i' may not be followed by another 'i'.
  • Each vowel 'o' may only be followed by an 'i' or a 'u'.
  • Each vowel 'u' may only be followed by an 'a'.

Since the answer may be too large, return it modulo 10^9 + 7.github

 

Example 1:微信

Input: n = 1
Output: 5
Explanation: All possible strings are: "a", "e", "i" , "o" and "u".

Example 2:spa

Input: n = 2
Output: 10
Explanation: All possible strings are: "ae", "ea", "ei", "ia", "ie", "io", "iu", "oi", "ou" and "ua".

Example 3: code

Input: n = 5
Output: 68

 

Constraints:orm

  • 1 <= n <= 2 * 10^4

給你一個整數 n,請你幫忙統計一下咱們能夠按下述規則造成多少個長度爲 n 的字符串:htm

  • 字符串中的每一個字符都應當是小寫元音字母('a''e''i''o''u'
  • 每一個元音 'a' 後面都只能跟着 'e'
  • 每一個元音 'e' 後面只能跟着 'a' 或者是 'i'
  • 每一個元音 'i' 後面 不能 再跟着另外一個 'i'
  • 每一個元音 'o' 後面只能跟着 'i' 或者是 'u'
  • 每一個元音 'u' 後面只能跟着 'a'

因爲答案可能會很大,因此請你返回 模 10^9 + 7 以後的結果。blog

 

示例 1:字符串

輸入:n = 1
輸出:5
解釋:全部可能的字符串分別是:"a", "e", "i" , "o" 和 "u"。

示例 2:

輸入:n = 2
輸出:10
解釋:全部可能的字符串分別是:"ae", "ea", "ei", "ia", "ie", "io", "iu", "oi", "ou" 和 "ua"。

示例 3:

輸入:n = 5
輸出:68

 

提示:

  • 1 <= n <= 2 * 10^4

Runtime: 100 ms
Memory Usage: 21.2 MB
 1 class Solution {
 2     func countVowelPermutation(_ n: Int) -> Int {
 3         var dp:[[Int]] = [[Int]](repeating: [Int](repeating: 0, count: 5), count: n + 1)
 4         let MOD:Int = 1000000007
 5         for i in 0..<5
 6         {
 7             dp[1][i] = 1
 8         }
 9         for i in 1..<n
10         {
11             dp[i+1][0] = (dp[i][1] + dp[i][2] + dp[i][4]) % MOD
12             dp[i+1][1] = (dp[i][0] + dp[i][2]) % MOD
13             dp[i+1][2] = (dp[i][1] + dp[i][3]) % MOD
14             dp[i+1][3] = dp[i][2]
15             dp[i+1][4] = (dp[i][2] + dp[i][3]) % MOD
16         }
17         var res:Int = 0
18         for i in 0..<5
19         {
20             res = (res + dp[n][i]) % MOD
21         }
22         return res
23     }
24 }
相關文章
相關標籤/搜索