假设我们有一个数字 n,我们必须找到大小为 n 且仅由元音 (a, e, i, o, u) 组成的字符串的数量,并且它们按字典顺序排列。当对于所有有效索引 i,s[i] 与字母表中的 s[i+1] 相同或位于 s[i+1] 之前,我们可以说字符串 s 是按字典顺序排序的。
所以,如果输入像 n = 2,那么输出将是 15,因为有很多字符串像 ["aa", "ae", "ai", "ao", "au", "ee", "ei ", "eo", "eu", "ii", "io", "iu", "oo", "ou", "uu"]。
让我们看看以下实现以获得更好的理解 -
def solve(n): if n==1: return 5 count = [1 for i in range(6)] for i in range(3,n+1): count[1] = count[1]+count[2]+count[3]+count[4]+count[5] count[2] = count[2]+count[3]+count[4]+count[5] count[3] = count[3]+count[4]+count[5] count[4] = count[4]+count[5] total = 0 for i in range(1,6): total += i*count[i] return total n = 2 print(solve(n))
2输出结果
15