b_lc_统计字典序元音字符串的数目(bfs / 递推)

给你一个整数 n,请返回长度为 n 、仅由元音 (a, e, i, o, u) 组成且按 字典序排列 的字符串数量。

char m[5]={'a','e','i','o','u'};
class Solution {
public:
    struct node {
        char c;
        int len;
    };
    int countVowelStrings(int n) {
        int ans=0;
        queue<node> q;
        for (char& t : m) q.push({t,1});
        while (!q.empty()) {
            node now=q.front(); q.pop();
            if (now.len==n) ans++;
            if (now.len>n) break;
            for (char& t : m) if (t>=now.c) {
                q.push({t,now.len+1});
            }
        }
        return ans;
    }
};

思路:比赛写的暴力bfs(40/41),但是超时使我的灵感来了
f[i][j]表示长度为i且以字符j为结尾的方案数,f[i][j]+=f[i-1][k](k<=j)

class Solution {
public:
    int ans,f[55][55];
    int countVowelStrings(int n) {
        for (int j=0; j<5; j++) f[1][j]=1;
        for (int i=2; i<=n; i++)
        for (int j=0; j<5; j++)
        for (int k=0; k<=j; k++)
            f[i][j]+=f[i-1][k];
        for (int j=0; j<5; j++) ans+=f[n][j];
        return ans;
    }
};

还有时、空都更优的解法,f[j]表示以字符j结尾的方案数,f[j]=f[j]+f[j-1]

class Solution {
public:
    int ans, f[55];
    int countVowelStrings(int n) {
        for (int j=0; j<5; j++) f[j]=1;
        for (int i=1; i<n; i++)
        for (int j=1; j<5; j++)
            f[j]+=f[j-1];
        for (int j=0; j<5; j++) ans+=f[j];
        return ans;
    }
};
原文地址:https://www.cnblogs.com/wdt1/p/13910739.html