【LeetCode 1220】 Count Vowels Permutation
題目描述
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(chǎn)’, ‘e’, ‘i’, ‘o’, ‘u’)
Each vowel ‘a(chǎn)’ may only be followed by an ‘e’.
Each vowel ‘e’ may only be followed by an ‘a(chǎn)’ 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(chǎn)’.
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: 68Constraints:
1 <= n <= 2 * 10^4
思路
動(dòng)態(tài)規(guī)劃。dp[i][j]表示長(zhǎng)度為i,以j為結(jié)尾,的串,個(gè)數(shù)。
根據(jù)限制條件可以推出每個(gè)字符前邊的字符是什么,以當(dāng)前字符結(jié)尾的個(gè)數(shù)為所有它前面可以出現(xiàn)的字符的個(gè)數(shù)之和。
代碼
class Solution { public:int countVowelPermutation(int n) {int MOD = 1e9+7;vector<vector<long long int> > dp(n+1, vector<long long>(5+1, 0));for (int i=1; i<=5; ++i) {dp[1][i] = 1;}for (int i=2; i<=n; ++i) {for (int j=1; j<=5; ++j) {long long tmp = 0;if (j == 1) {tmp = (dp[i-1][2]%MOD + dp[i-1][3]%MOD + dp[i-1][5]%MOD)%MOD;}else if (j == 2) {tmp = (dp[i-1][3]%MOD + dp[i-1][1]%MOD)%MOD;}else if (j == 3) {tmp = (dp[i-1][4]%MOD + dp[i-1][2]%MOD)%MOD;}else if (j == 4) {tmp = dp[i-1][3]%MOD;}else {tmp = (dp[i-1][3]%MOD + dp[i-1][4]%MOD);}dp[i][j] += tmp;dp[i][j] %= MOD;}}long long res = 0;for (int i=1; i<=5; ++i) {res += dp[n][i];res %= MOD;}return res;} };最后不能直接求和然后取模,會(huì)超long long。
動(dòng)態(tài)規(guī)劃修行告一段落。甚至感覺比大學(xué)的時(shí)候理解的更深一點(diǎn)。
洗漱睡覺嘍。
總結(jié)
以上是生活随笔為你收集整理的【LeetCode 1220】 Count Vowels Permutation的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 弹窗php整人_[整人小程序] 超级信息
- 下一篇: paddlehub 使用体验-视频抠图_