zoukankan      html  css  js  c++  java
  • 600. 不含连续1的非负整数

    600. 不含连续1的非负整数

    给定一个正整数 n,找出小于或等于 n 的非负整数中,其二进制表示不包含 连续的1 的个数。

    示例 1:

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

    说明: 1 <= n <= 109

     1 class Solution {
     2 public:
     3     //数位DP
     4     int dp[32][2];
     5     int data[32];//存的位数 值  如 234 ->  4,3,2
     6     int dfs(int pos,bool pre,bool limit){//int pre, limit可以改成int , pre代表前一个是否是1 ,limit代表是否是 上届
     7         if(pos==-1) return 1;//判断边界
     8         if(!limit&&dp[pos][pre]!=-1) return dp[pos][pre];//记忆化搜索 :pre 可以是Int 类型的,然后 新加一个 bool state 来 判断,  dp[pos][state]; for循环里面则位 if(pre==1&&i==1) ;res+=dfs(pos-1,i,i==1,limit&&i==data[pos]);
     9         int res=0;//存结果
    10         int up=limit?data[pos]:1;//判断上界
    11         for(int i=0;i<=up;i++){
    12             if(pre&&i==1) continue;// 是11 则跳过
    13             res+=dfs(pos-1,i==1,limit&&i==data[pos]);
    14         }
    15         if(!limit) dp[pos][pre]=res;
    16         return res;
    17 
    18     }
    19     int solve(int num){
    20         int k=0;//从0开始存储
    21         while(num){
    22             data[k++]=num%2;
    23             //num/=2;//或者
    24             num>>=1;//右移动,也是除以2^1
    25         }
    26         return dfs(k-1,false,true);
    27     }
    28     int findIntegers(int num) {
    29         memset(dp,-1,sizeof(dp));
    30         return solve(num);
    31     }
    32 };
  • 相关阅读:
    python运行出现TypeError: super() takes at least 1 argument (0 given)错误
    python使用Pyinstaller打包
    python 将字符串中的unicode字符码转换成字符
    python 复制列表
    AetherUpload大文件传输
    phpstom激活
    BusyBox telnetd配置
    MDK链接脚本错误
    利用mass storage class 做免驱动usb设备.
    BMP图片的解析,关于压缩方式
  • 原文地址:https://www.cnblogs.com/NirobertEinteson/p/12534889.html
Copyright © 2011-2022 走看看