(Translated by https://www.hiragana.jp/)
davidgao7.github.io/_posts/2021-09-21-count-vowel-strings.md at master · davidgao7/davidgao7.github.io · GitHub
Skip to content

Latest commit

 

History

History
55 lines (47 loc) · 1.52 KB

2021-09-21-count-vowel-strings.md

File metadata and controls

55 lines (47 loc) · 1.52 KB
title date permalink tags
count sorted vowel strings
2021-09-21
/posts/2021/09/count-vowel-strings/
dynamic programming

统计字典じてんじょもと音字おんじくしてきすうもく

题目描述

给你いち个整すうn, 请返かい长度为 n ,仅由もとおとa,e,i,o,u 组成且按字典じてんじょ排列はいれつてきくし数量すうりょう

くし s 按 字典じてんじょ排列はいれつ 需要じゅよう满足:对于所有しょゆう有效ゆうこうてき i,s[i] ざい字母じぼひょうちゅうてき位置いち总是あずか s[i+1] あいどうあるざい s[i+1] まえ

输入:n = 1
输出:5
かい释:仅由もとおと组成てき 5 个字典じてんじょくし为 ["a","e","i","o","u"]

输入:n = 2
输出:15
かい释:仅由もとおと组成てき 15 个字典じてんじょくし为
["aa","ae","ai","ao","au","ee","ei","eo","eu","ii","io","iu","oo","ou","uu"]
注意ちゅうい,"ea" 符合ふごう题意てきくしいん为 'e' ざい字母じぼひょうちゅうてき位置いち 'a' もたれきさき

输入:n = 33
输出:66045

解法かいほういち: 无脑数学すうがく

とう价于n个字ははぶん给五种元おん,且分配ぶんぱいすうもく以为れい,就是もとめc(n+4, n) = c(n+4, 4)

class Solution {
public:
    int countVowelStrings(int n) {
        if (n == 1) return 5;
        return (n + 4) * (n + 3) * (n + 2) * (n + 1) / 24;
    }
};

解法かいほう: 动态规划

a以加ざい(aeiou)まえ,e以加ざい(eiou)まえ,以此类推

就是もとめn-1まえ缀和

class Solution {
public:
    int countVowelStrings(int n) {
        vector<int> cnt(5, 1);
        while(--n) partial_sum(begin(cnt), end(cnt), begin(cnt));
        return accumulate(begin(cnt), end(cnt), 0);
    }
};