leetcode算法题--统计范围内的步进数字数目

原题链接:https://leetcode.cn/problems/count-stepping-numbers-in-range/description/

数位dp题目,需要稍微做下变更

const mod int = 1e9 + 7 
func countSteppingNumbers(low string, high string) int {
    ans := (calc(high) - calc(low) + mod) % mod // +mod 防止算出负数
	if valid(low) {
		ans = (ans + 1) % mod
	}
	return int(ans)
}

func valid(s string) bool {
	for i := 1; i < len(s); i++ {
		if abs(int(s[i-1]), int(s[i])) != 1 {
			return false
		}
	}
	return true
}

func calc(s string) int { 
    n := len(s)
    memo := make([][10]int, n)
    for i := range memo {
        for j := range memo[i] {
            memo[i][j] = -1
        }
    }
    var dfs func(i, last int, isLimit, isSkip bool) int
    dfs = func(i, last int, isLimit, isSkip bool) int {
        if i >= n {
            if !isSkip {
                return 1
            }
            return 0
        } 

        if !isLimit && !isSkip && memo[i][last] != -1 {
            return memo[i][last]
        }

        var res int = 0 
        l := 0
        if isSkip {
            res = (res + dfs(i+1, last, false, true)) % mod
            l = 1
        }
        h := 9 
        if isLimit {
            h = int(s[i] - '0')    
        }
        for j := l; j <= h; j ++ {
            if isSkip || abs(last, j) == 1 {
                res = (res + dfs(i+1, j, isLimit && j == h, false)) % mod
            }  
        }
        if !isLimit && !isSkip {
            memo[i][last] = res;
        }
        return res
    } 
    return dfs(0, 0, true, true)
}

func abs(a, b int) int {
    if a > b {
        return a - b
    }

    return b - a
}

注意有几个坑

  1. 这题的数据比较严格,所以需要注意valid处的检查

你可能感兴趣的:(Algorithm,算法,leetcode,职场和发展)