leetcode:1220. 统计元音字母序列的数目

链接:
https://leetcode-cn.com/problems/count-vowels-permutation/
这是一道比较简单的hard题,考虑各个元音结尾时前一位可能的情况,递推即可。

class Solution {
    public int countVowelPermutation(int n) {
        int dp[] = new int [5];
        for(int i = 0;i<5;i++)
            dp[i] =  1; // n = 1 时,以每个元音结尾仅1中可能

        for(int i = 2;i<=n;i++)
        {
            int temp[] = new int [5];
            temp[0] = (dp[1]+dp[2]) %1000000007;
            temp[0] = (temp[0] + dp[4]) % 1000000007;   // a为结尾,前一位可能是e,i,u,注意整形可能溢出
            temp[1] = (dp[0]+dp[2]) %1000000007;    
            temp[2] = (dp[1]+dp[3]) %1000000007;
            temp[3] = (dp[2]) %1000000007;
            temp[4] = (dp[2]+dp[3]) %1000000007;
            for(int j = 0;j<5;j++)
                dp[j] = temp[j];
        }
        for(int i = 1;i<5;i++)
            dp[0] =  (dp[0]+dp[i])%1000000007;
        return dp[0];
    }
}

你可能感兴趣的:(leetcode,算法,leetcode)