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
Solution: DP
dp[i][j] := # of strings of length i ends with j.
dp[i][j] = sum(dp[i – 1][[k]) 0 <= k <= j
Time complexity: O(n)
Space complexity: O(n) -> O(1)
C++/O(n) Space
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class Solution { public: int countVowelStrings(int n) { // dp[i][j] = # of strings of length i ends with j vector<vector<int>> dp(n + 1, vector<int>(5, 1)); for (int i = 2; i <= n; ++i) { int s = 0; for (int j = 0; j < 5; ++j) { s += dp[i - 1][j]; dp[i][j] = s; } } return accumulate(begin(dp[n]), end(dp[n]), 0); } }; |
C++/O(1) Space
1 2 3 4 5 6 7 8 9 10 11 12 |
class Solution { public: int countVowelStrings(int n) { // dp([i])[j] = # of strings of length i ends with j vector<int> dp(5, 1); for (int i = 2; i <= n; ++i) for (int j = 4; j >= 0; --j) for (int k = 0; k < j; ++k) dp[j] += dp[k]; return accumulate(begin(dp), end(dp), 0); } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment