1641. Count Sorted Vowel Strings (M)

Count Sorted Vowel Strings (M)

题目

Given an integer n, return the number of strings of length n that consist only of vowels (a, e, i, o, u) and are lexicographically sorted.

A string s is lexicographically sorted if for all valid i, s[i] is the same as or comes before s[i+1] in the alphabet.

Example 1:

Input: n = 1
Output: 5
Explanation: The 5 sorted strings that consist of vowels only are ["a","e","i","o","u"].

Example 2:

Input: n = 2
Output: 15
Explanation: The 15 sorted strings that consist of vowels only are
["aa","ae","ai","ao","au","ee","ei","eo","eu","ii","io","iu","oo","ou","uu"].
Note that "ea" is not a valid string since 'e' comes after 'a' in the alphabet.

Example 3:

Input: n = 33
Output: 66045

Constraints:

  • 1 <= n <= 50

题意

用5个元音字母"aeiou"组成长度为n的字符串,要求排在前面的字母在字符串中同样要排在前面,求这样的字符串的个数。

思路

动态规划。用0-4来表示5个字母,dp[n][i]表示长度为n且结尾为i的字符串。可以得到递推公式:

\[dp[n][i]=\sum_{j\le i}dp[n-1][j] \]

最后对dp[n][0-4]求和即可。


代码实现

Java

class Solution {
    public int countVowelStrings(int n) {
        int[][] dp = new int[n + 1][5];
        for (int i = 0; i < 5; i++) {
            dp[1][i] = 1;
        }
        for (int i = 2; i <= n; i++) {
            for (int j = 0; j < 5; j++) {
                for (int k = 0; k <= j; k++) {
                    dp[i][j] += dp[i - 1][k];
                }
            }
        }
        int sum = 0;
        for (int i = 0; i < 5; i++) {
            sum += dp[n][i];
        }
        return sum;
    }
}
posted @ 2021-01-18 20:13  墨云黑  阅读(206)  评论(0编辑  收藏  举报