题目

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:

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

Example 2:

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

Example 3:

  1. Input: n = 33
  2. Output: 66045

Constraints:

  • 1 <= n <= 50

题意

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

思路

动态规划。用0-4来表示5个字母,dp[n][i]表示长度为n且结尾为i的字符串。可以得到递推公式:
1641. Count Sorted Vowel Strings (M) - 图1
最后对dp[n][0-4]求和即可。


代码实现

Java

  1. class Solution {
  2. public int countVowelStrings(int n) {
  3. int[][] dp = new int[n + 1][5];
  4. for (int i = 0; i < 5; i++) {
  5. dp[1][i] = 1;
  6. }
  7. for (int i = 2; i <= n; i++) {
  8. for (int j = 0; j < 5; j++) {
  9. for (int k = 0; k <= j; k++) {
  10. dp[i][j] += dp[i - 1][k];
  11. }
  12. }
  13. }
  14. int sum = 0;
  15. for (int i = 0; i < 5; i++) {
  16. sum += dp[n][i];
  17. }
  18. return sum;
  19. }
  20. }