LeetCode //C - 1220. Count Vowels Permutation

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', '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

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

From: LeetCode

Link: 1220. Count Vowels Permutation


Solution:

Ideas:

keep counts of strings ending with each vowel, then update by reverse rules.

Code:
c 复制代码
int countVowelPermutation(int n) {
    const long MOD = 1000000007;

    long a = 1, e = 1, i = 1, o = 1, u = 1;

    for (int len = 2; len <= n; len++) {
        long na = (e + i + u) % MOD;      // previous e/i/u can go to a
        long ne = (a + i) % MOD;          // previous a/i can go to e
        long ni = (e + o) % MOD;          // previous e/o can go to i
        long no = i % MOD;                // previous i can go to o
        long nu = (i + o) % MOD;          // previous i/o can go to u

        a = na;
        e = ne;
        i = ni;
        o = no;
        u = nu;
    }

    return (int)((a + e + i + o + u) % MOD);
}
相关推荐
码爸4 分钟前
贪心算法介绍与示例
算法·贪心算法
-dzk-22 分钟前
【多维动态规划】LC 64.最小路径和
算法·动态规划
垆边人似月.1 小时前
华为机试题 :字符串压缩
算法·华为
ggb喔1 小时前
52pojie 的图片工具:为什么无损转换后体积涨了 6 倍、照片方向还是歪的
图像处理·python·算法·计算机视觉·图形渲染·媒体
小小龙学IT1 小时前
Go 语言 cgo 与 C/C++ 互操作深度解析:从 fwlib 直连到工业数采网关实战系列
c语言·c++·golang
菜鸟~noob2332 小时前
【电子战】第25篇:自由空间、双射线与菲涅尔区【含matlab代码】
开发语言·算法·matlab
地平线开发者2 小时前
地平线征程6M YOLOv8s 部署
算法·自动驾驶
Run_Teenage2 小时前
算法:Manacher(马拉车)算法、中心扩展算法
算法
Tisfy2 小时前
LeetCode 0301.删除无效的括号:二进制枚举 / 回溯
算法·leetcode·字符串·题解·回溯·括号匹配·二进制枚举
Nil2083 小时前
leetcode 322零钱兑换
算法·leetcode·职场和发展