Skip to content

1641. Count Sorted Vowel Strings 👍

Approach 1: DP

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  int countVowelStrings(int n) {
    // dp[0] := the number of lexicographically sorted string that end in 'a'
    // dp[1] := the number of lexicographically sorted string that end in 'e'
    // dp[2] := the number of lexicographically sorted string that end in 'i'
    // dp[3] := the number of lexicographically sorted string that end in 'o'
    // dp[4] := the number of lexicographically sorted string that end in 'u'
    vector<int> dp(5, 1);

    for (int i = 2; i <= n; ++i) {
      vector<int> newDp(5);
      for (int j = 0; j < 5; ++j)
        for (int k = 0; k <= j; ++k)
          newDp[j] += dp[k];
      dp = std::move(newDp);
    }

    return accumulate(dp.begin(), dp.end(), 0);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
  public int countVowelStrings(int n) {
    // dp[0] := the number of lexicographically sorted string that end in 'a'
    // dp[1] := the number of lexicographically sorted string that end in 'e'
    // dp[2] := the number of lexicographically sorted string that end in 'i'
    // dp[3] := the number of lexicographically sorted string that end in 'o'
    // dp[4] := the number of lexicographically sorted string that end in 'u'
    int[] dp = new int[5];
    Arrays.fill(dp, 1);

    for (int i = 2; i <= n; ++i) {
      int[] newDp = new int[5];
      for (int j = 0; j < 5; ++j)
        for (int k = 0; k <= j; ++k)
          newDp[j] += dp[k];
      dp = newDp;
    }

    return Arrays.stream(dp).sum();
  }
}

Approach 2: Math

  • Time: $O(1)$
  • Space: $O(1)$
1
2
3
4
5
6
class Solution {
 public:
  int countVowelStrings(int n) {
    return (n + 4) * (n + 3) * (n + 2) * (n + 1) / 24;
  }
};
1
2
3
4
5
class Solution {
  public int countVowelStrings(int n) {
    return (n + 4) * (n + 3) * (n + 2) * (n + 1) / 24;
  }
}