题目
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
解析
一维的DP解不难, 就不多说了. 说说解析解.
这道题可以这样理解: 有5个盒子, 上面写着["a","e","i","o","u"]
, 有n个球放入5个盒子,盒子可以为空, 有多少种方法?
因为题目要求string为字典序,所以当组成字符串的所有字符确定了,顺序也就确定了.
盒子不为空的情况
把n个球放成一排, 插入4个隔板, 把n个小球分成5份, 板子有多少种插法?
因为盒子不为空,所以两个球之间和左右末端不能插入多个隔板. 所以有n - 1个位置插入隔板. 所以答案为 comb(n - 1 , 5 - 1)
盒子可为空的情况
先从n + 5
个球中拿出5个, 在5个盒子里各放一个球, 然后再放原来的n个球. 等价于n个球放入5个盒子且盒子可以为空. 此时答案为comb(n + 5 - 1, 5 - 1)
排列组合公式
Permutation: $nP_k = \frac{n!}{(n-k)!}$
Combination: $nC_k = \frac{nP_k}{k!}$
代码
1 | class Solution { |