• 数位DP600. 不含连续1的非负整数


    问题描述

    给定一个正整数 n ,返回范围在 [0, n] 都非负整数中,其二进制表示不包含 连续的 1 的个数。

    示例 1:

    输入: n = 5
    输出: 5
    解释:
    下面是带有相应二进制表示的非负整数<= 5:
    0 : 0
    1 : 1
    2 : 10
    3 : 11
    4 : 100
    5 : 101
    其中,只有整数3违反规则(有两个连续的1),其他5个满足规则。
    示例 2:

    输入: n = 1
    输出: 2
    示例 3:

    输入: n = 2
    输出: 3

    提示:

    1 <= n <= 109

    问题求解

    class Solution:
        def findIntegers(self, n: int) -> int:
            s = "{:b}".format(n)
            
            @cache
            def f(i, is_limit, prev):
                if i == len(s):
                    return 1
                
                res = 0
                up = int(s[i]) if is_limit else 1
    
                for d in range(0, up + 1):
                    if d == 1 and prev == 1:
                        continue
                    res += f(i + 1, is_limit and d == up, d)
                
                return res
            
            return f(0, True, 0)
    
  • 相关阅读:
    url 编码与解码
    调硬件开门
    JsBridge 开灯关灯
    滚动条样式
    uni-app 组件传值及插槽
    Eapp 调接口及跳转
    uni-app 的基础格式
    Eapp 几个弹框
    flexible 移动端适配
    mongodb恢复备份
  • 原文地址:https://www.cnblogs.com/hyserendipity/p/16586426.html
Copyright © 2020-2023  润新知