每日一题:1220. 统计元音字母序列的数目(Count Vowels Permutation)
這題是7/4/2021英文站leetcode的每日一題, 想把自己的想法和思路記錄下來.
題目:
Given an integer?n, your task is to count how many strings of length?n?can be formed under the following rules:
- 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.
Example 1:
Input: n = 1 Output: 5 Explanation: All possible strings are: "a", "e", "i" , "o" and "u".Example 2:
Input: n = 2 Output: 10 Explanation: All possible strings are: "ae", "ea", "ei", "ia", "ie", "io", "iu", "oi", "ou" and "ua".Example 3:?
Input: n = 5 Output: 68思路:
看到題我的第一個想法是用backtracking,因為之前用backtracking做過其他permutation的題.但是看到數據量(1<=n<=2*10^4)我就放棄了,用backtracking做絕對超時. 于是根據提示,我的新想法是用動態規劃去做.
重新梳理了題目之后發現需要返回的結果是總數,不是可能的permutation. 那么動態規劃確實是一個很好的方法. 一開始的思路是用一個大小是(n,6)2d的array去存儲所有可能解的數量, 每一行存儲當前長度下(1 - n) 每個原音字母的所有permutation長度,前五個列分別代表五個元音字母,第六列存儲最后的permutation總數之和。從1開始,每行每列根據array里先前的數值遞增,直到長度為n。最后返回第六列所有數值之和%(10^9+7)。想的很美,但是在實現時問題不少。 例如每個元音的可能的permutation長度其實和本身之前的permuta長度并沒有關系,每個元音生成permutation的方法也不一樣。于是我放棄了這個方法。
參考完官方的解之后,我發現我的第一步是沒錯的,可以用類似的方法去解,但是需要將每一個元音的permutation長度分開,存儲為5個長度為n的1d的array。參考官方解提供的每個元音與其他的元音序列的關系,每個元音序列的更新算式也就出來了
圖1: 每個元音序列的關系 (https://leetcode.com/problems/count-vowels-permutation/solution/)
a的可能的序列 = e,i,和u的前一個序列的總和,因為他們后面可以跟a
e的可能的序列 = a,i的前一個序列的總和,因為他們后面可以跟e
以此類推。。。
在更新完這五個permutation的array之后,將他們最后的值相加,再%10*9+7就可以得到結果了
代碼:(c++)
class Solution { public:int mod = 1000000007;int countVowelPermutation(int n) {vector<long> aCount(n,1);vector<long> eCount(n,1);vector<long> iCount(n,1);vector<long> oCount(n,1);vector<long> uCount(n,1);for (int i=1; i < n; i++){aCount[i] =(eCount[i-1]+iCount[i-1]+uCount[i-1])%mod;eCount[i] = (aCount[i-1]+iCount[i-1])%mod;iCount[i] = (eCount[i-1]+oCount[i-1])%mod;oCount[i] = (iCount[i-1])%mod;uCount[i] = (iCount[i-1]+oCount[i-1])%mod;}long res = (aCount[n-1]+eCount[n-1]+iCount[n-1]+oCount[n-1]+uCount[n-1])%mod;return (int)res;} };結果:
總結
以上是生活随笔為你收集整理的每日一题:1220. 统计元音字母序列的数目(Count Vowels Permutation)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: gcc oracle mysql_Lin
- 下一篇: 视频抠图在线工具有哪些?推荐这3款AI智