1220. 统计元音字母序列的数目

59 阅读1分钟

题目:
leetcode.cn/problems/co…
算法:
方法一:暴力搜索 超时

func countVowelPermutation(n int) int {
    count := 0

    var dfs func(pre int,  length int) 
    dfs = func(pre int, length int) {
        if length == n {
            count = (count + 1) % 1000000007
            return
        }
        switch pre {
            case 0:
                dfs(1, length + 1)
            case 1:
                dfs(0, length + 1)
                dfs(2, length + 1)
            case 2:
                dfs(0, length + 1)
                dfs(1, length + 1)
                dfs(3, length + 1)
                dfs(4, length + 1)
            case 3:
                dfs(2, length + 1)
                dfs(4, length + 1)
            case 4:
                dfs(0, length + 1)
        }
    }
    for i := 0; i <= 4; i ++ {
        dfs(i, 1)
    }
    return count
}

方法二:状态机/动态规划

func countVowelPermutation(n int) int {
    count := 0
    state := make([][]int, 2)
    for i := range state {
        state[i] = make([]int, 5)
    }
    for i := range state[0] {
        state[0][i] = 1
    }
    // fmt.Println(state)
    mod := 1000000007
    for i := 2; i <= n; i ++ {
        state[1][0] = (state[0][1] + state[0][2] + state[0][4]) % mod
        state[1][1] = (state[0][0] + state[0][2]) % mod
        state[1][2] = (state[0][1] + state[0][3]) % mod
        state[1][3] = (state[0][2]) % mod
        state[1][4] = (state[0][2] + state[0][3]) % mod
        copy(state[0], state[1])
    }
    for i := range state[0] {
        count = (count + state[0][i])% mod
    }
    return count
}