首页 > 其他 > 详细

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

时间:2020-11-01 22:13:18      阅读:21      评论:0      收藏:0      [点我收藏+]

给你一个整数 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;
    }
};

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

原文:https://www.cnblogs.com/wdt1/p/13910739.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!