[Leetcode Daily Notes] 1641. Count the number of vowel strings in dictionary order (Python)

topic

Give you an integer n, please return the number of strings with length n and consisting only of vowels (a, e, i, o, u) and arranged in lexicographic order.

The string s should be arranged in lexicographic order: for all valid i, the position of s[i] in the alphabet is always the same as s[i+1] or before s[i+1].

Example 1:

Input: n = 1 Output: 5 Explanation: The 5 lexicographical strings consisting only of vowels are ["a","e","i","o","u"]

Example 2:

Input: n = 2 Output: 15 Explanation: 15 lexicographical strings composed of only vowels are
["aa","ae","ai","ao","au","ee","ei ","Eo","eu","ii","io","iu","oo","ou","uu"]
Note that "ea" is not a string that meets the meaning of the title, because'e 'Is behind'a' in the alphabet

Example 3:

Input: n = 33 Output: 66045

Problem-solving ideas

Dynamic programming

State definition

dp[i][j]Represents the number of characters ending with the j-th vowel in the i-th round. For example, the number of characters ending with dp[0][2]"i" in the 0th round is 1;
at the same time, it can be found that the number of each round is only Related to the previous round, then you can directly use a one-dimensional array to dp[i]represent the number of the i-th letter as the end of the string;

State transition equation

["A", "e", "i", "o", "u"], if you want to add "e", you can find that you can only add it after "a" and "e", that is, dp [1][1] = dp[0][1]+dp[0][0], similarly dp[1][2] = dp[0][0]+dp[0][1]+dp [0][2], and so on, then converted to a one-dimensional array can be found dp[1] += dp[0], dp[2] += dp[1].
Get state transition equationdp[i] += dp[i-1]

Code

class Solution:
    def countVowelStrings(self, n: int) -> int:
        dp = [1,1,1,1,1]
        for _ in range(n-1):
            for i in range(1,5):
                dp[i] += dp[i-1]
        return sum(dp)

Guess you like

Origin blog.csdn.net/qq_36477513/article/details/111509152