【数位dp】【C++算法】600. 不含连续1的非负整数

简介: 【数位dp】【C++算法】600. 不含连续1的非负整数

作者推荐

【矩阵快速幂】封装类及测试用例及样例

涉及知识点

数位dp

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

给定一个正整数 n ,请你统计在 [0, n] 范围的非负整数中,有多少个整数的二进制表示中不存在 连续的 1 。

示例 1:

输入: n = 5

输出: 5

解释:

下面列出范围在 [0, 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

数位dp

直接使用封装好的类。

结果:int 最小值:‘0’ 最大值:‘1’

当前值为’1’时,前值必须为‘0’。

当前值为’0’时,前值‘0’ ‘1’ 皆可。

代码

封装类

template<class ELE, class ResultType, ELE minEle, ELE maxEle>
class CLowUperr
{
public:
  CLowUperr(int iResutlCount):m_iResutlCount(iResutlCount)
  {
  }
  void Init(const ELE* pLower, const ELE* pHigh, int iNum)
  {
    m_vPre.assign(4, vector<ResultType>(m_iResutlCount));
    if (iNum <= 0)
    {
      return;
    }
    InitPre(pLower, pHigh);
    iNum--;
    while (iNum--)
    {
      pLower++;
      pHigh++;
      vector<vector<ResultType>> dp(4, vector<ResultType>(m_iResutlCount));
      OnInitDP(dp);
      //处理非边界
      for (auto tmp = minEle; tmp <= maxEle; tmp++)
      {
        OnEnumOtherBit(dp[0], m_vPre[0], tmp);
      }
      //处理下边界
      OnEnumOtherBit(dp[1], m_vPre[1], *pLower);
      for (auto tmp = *pLower + 1; tmp <= maxEle; tmp++)
      {
        OnEnumOtherBit(dp[0], m_vPre[1], tmp );
      }
      //处理上边界
      OnEnumOtherBit(dp[2], m_vPre[2], *pHigh );
      for (auto tmp = minEle; tmp < *pHigh; tmp++)
      {
        OnEnumOtherBit(dp[0], m_vPre[2], tmp );
      }
      //处理上下边界
      if (*pLower == *pHigh)
      {
        OnEnumOtherBit(dp[3], m_vPre[3], *pLower);
      }
      else
      {
        OnEnumOtherBit(dp[1], m_vPre[3], *pLower );
        for (auto tmp = *pLower + 1; tmp < *pHigh; tmp++)
        {
          OnEnumOtherBit(dp[0], m_vPre[3], tmp );
        }
        OnEnumOtherBit(dp[2], m_vPre[3], *pHigh );
      }
      m_vPre.swap(dp);
    }
  }
  /*ResultType Total(int iMinIndex, int iMaxIndex)
  {
    ResultType ret;
    for (int status = 0; status < 4; status++)
    {
      for (int index = iMinIndex; index <= iMaxIndex; index++)
      {
        ret += m_vPre[status][index];
      }
    }
    return ret;
  }*/
protected:
  const int m_iResutlCount;
  void InitPre(const ELE* const pLower, const ELE* const pHigh)
  {
    for (ELE cur = *pLower; cur <= *pHigh; cur++)
    {
      int iStatus = 0;
      if (*pLower == cur)
      {
        iStatus = *pLower == *pHigh ? 3 : 1;
      }
      else if (*pHigh == cur)
      {
        iStatus = 2;
      }
      OnEnumFirstBit(m_vPre[iStatus], cur);
    }
  }
  virtual void OnEnumOtherBit(vector<ResultType>& dp, const vector<ResultType>& vPre, ELE curValue) = 0;
  virtual void OnEnumFirstBit(vector<ResultType>& vPre, const ELE curValue) = 0;
  virtual void OnInitDP(vector<vector<ResultType>>& dp)
  {
  }
  vector<vector<ResultType>> m_vPre;
};

核心代码

class CCharLowerUper : public CLowUperr<char, int, '0', '1'>
{
public:
  using CLowUperr<char, int, '0', '1'>::CLowUperr;
  int Total(int iMinIndex, int iMaxIndex)
  {
    int ret = 0;
    for (int index = iMinIndex; index <= iMaxIndex; index++)
    {
      int cur = 0;
      for (int status = 0; status < 4; status++)
      {
        cur += m_vPre[status][index];
      }
      ret += cur;
    }
    return ret;
  }
protected:
  virtual void OnEnumFirstBit(vector<int>& vPre, const char curValue)
  {
    const int index = curValue - '0';
    vPre[index]++;
  }
  virtual void OnEnumOtherBit(vector<int>& dp, const vector<int>& vPre, char curValue)
  {
    const int index = curValue - '0';
    if (1 == index)
    {
      dp[index] += vPre[0];
    }
    else
    {
      dp[index] += vPre[0] + vPre[1];
    }   
  }
};
class Solution {
public:
  int findIntegers(int n) {
     string strN ;
     while (n > 0)
     {
       strN += ((n & 1) ? "1" : "0");
       n /= 2;
     }
     std::reverse(strN.begin(), strN.end());
    const int len = strN.length();
    int iRet = 0;
    for (int i = 1; i < len; i++)
    {
      CCharLowerUper lu(2);
      lu.Init(("1" + string(i - 1, '0')).c_str(), string(i, '1').c_str(), i);
      iRet += lu.Total(0, 1);
    }
    CCharLowerUper lu(2);
    lu.Init(("1" + string(len - 1, '0')).c_str(), strN.c_str(), len);
    iRet += lu.Total(0, 1);
    return 1 + iRet;
  } 
};

测试用例

template<class T>
void Assert(const T& t1, const T& t2)
{
  assert(t1 == t2);
}
template<class T>
void Assert(const vector<T>& v1, const vector<T>& v2)
{
  if (v1.size() != v2.size())
  {
    assert(false);
    return;
  }
  for (int i = 0; i < v1.size(); i++)
  {
    Assert(v1[i], v2[i]);
  }
}
int main()
{
  int n;
  {
    Solution sln;
    n = 5;
    auto res = sln.findIntegers(n);
    Assert(5, res);
  }
  {
    Solution sln;
    n = 1;
    auto res = sln.findIntegers(n);
    Assert(2, res);
  }
  {
    Solution sln;
    n = 2;
    auto res = sln.findIntegers(n);
    Assert(3, res);
  }
  {
    Solution sln;
    n = 10;
    auto res = sln.findIntegers(n);
    Assert(8, res);
  }
  {
    Solution sln;
    n = 100;
    auto res = sln.findIntegers(n);
    Assert(34, res);
  }
}

2013年1月版

class Solution {

public:

int findIntegers(int n) {

if (1 == n)

{

return 2;

}

std::vector bits;

int tmp = n;

while (tmp > 0)

{

bits.insert(bits.begin(), tmp % 2);

tmp >>= 1;

}

const int iBitNum = bits.size();

//dp[i][0]表示i位 0结尾的可能数

vector<vector> dp(iBitNum, vector(2));//

dp[1][0] = 1;

dp[1][1] = 1;

for (int i = 2; i < dp.size(); i++)

{

dp[i][0] = dp[i - 1][0] + dp[i - 1][1];

dp[i][1] = dp[i - 1][0];

}

int iNum = 0;// dp[iBitNum - 1][0] + dp[iBitNum - 1][1];

int iPreBit = 0;

for (int i = 0; i < iBitNum; i++)

{

const int iCurBit = bits[i];

if (i + 1 == iBitNum)

{

iNum += iCurBit ;

}

else

{

if (1 == iCurBit)

{

iNum += dp[iBitNum - i - 1][0] + dp[iBitNum - i - 1][1];

}

}

if (iCurBit & iPreBit)

{

break;

}

if (i + 1 == iBitNum)

{

iNum++;

}

iPreBit = iCurBit;

}

return iNum;

}

};


相关文章
|
30天前
|
负载均衡 算法 安全
探秘:基于 C++ 的局域网电脑控制软件自适应指令分发算法
在现代企业信息化架构中,局域网电脑控制软件如同“指挥官”,通过自适应指令分发算法动态调整指令发送节奏与数据量,确保不同性能的终端设备高效运行。基于C++语言,利用套接字实现稳定连接和线程同步管理,结合实时状态反馈,优化指令分发策略,提升整体管控效率,保障网络稳定,助力数字化办公。
51 19
|
1月前
|
存储 算法 测试技术
【C++数据结构——树】二叉树的遍历算法(头歌教学实验平台习题) 【合集】
本任务旨在实现二叉树的遍历,包括先序、中序、后序和层次遍历。首先介绍了二叉树的基本概念与结构定义,并通过C++代码示例展示了如何定义二叉树节点及构建二叉树。接着详细讲解了四种遍历方法的递归实现逻辑,以及层次遍历中队列的应用。最后提供了测试用例和预期输出,确保代码正确性。通过这些内容,帮助读者理解并掌握二叉树遍历的核心思想与实现技巧。
47 2
|
2月前
|
存储 算法 安全
基于红黑树的局域网上网行为控制C++ 算法解析
在当今网络环境中,局域网上网行为控制对企业和学校至关重要。本文探讨了一种基于红黑树数据结构的高效算法,用于管理用户的上网行为,如IP地址、上网时长、访问网站类别和流量使用情况。通过红黑树的自平衡特性,确保了高效的查找、插入和删除操作。文中提供了C++代码示例,展示了如何实现该算法,并强调其在网络管理中的应用价值。
|
1月前
|
存储 算法 安全
基于哈希表的文件共享平台 C++ 算法实现与分析
在数字化时代,文件共享平台不可或缺。本文探讨哈希表在文件共享中的应用,包括原理、优势及C++实现。哈希表通过键值对快速访问文件元数据(如文件名、大小、位置等),查找时间复杂度为O(1),显著提升查找速度和用户体验。代码示例展示了文件上传和搜索功能,实际应用中需解决哈希冲突、动态扩容和线程安全等问题,以优化性能。
|
2月前
|
算法 安全 C++
用 C++ 算法控制员工上网的软件,关键逻辑是啥?来深度解读下
在企业信息化管理中,控制员工上网的软件成为保障网络秩序与提升办公效率的关键工具。该软件基于C++语言,融合红黑树、令牌桶和滑动窗口等算法,实现网址精准过滤、流量均衡分配及异常连接监测。通过高效的数据结构与算法设计,确保企业网络资源优化配置与安全防护升级,同时尊重员工权益,助力企业数字化发展。
64 4
|
4月前
|
存储 算法 C++
高精度算法(加、减、乘、除,使用c++实现)
高精度算法(加、减、乘、除,使用c++实现)
1105 0
高精度算法(加、减、乘、除,使用c++实现)
|
4月前
|
算法 数据处理 C++
c++ STL划分算法;partition()、partition_copy()、stable_partition()、partition_point()详解
这些算法是C++ STL中处理和组织数据的强大工具,能够高效地实现复杂的数据处理逻辑。理解它们的差异和应用场景,将有助于编写更加高效和清晰的C++代码。
85 0
|
4月前
|
存储 算法
动态规划算法学习一:DP的重要知识点、矩阵连乘算法
这篇文章是关于动态规划算法中矩阵连乘问题的详解,包括问题描述、最优子结构、重叠子问题、递归方法、备忘录方法和动态规划算法设计的步骤。
246 0
|
4月前
|
存储 算法 决策智能
【算法】博弈论(C/C++)
【算法】博弈论(C/C++)
|
4月前
|
存储 算法 C++
【算法】哈希映射(C/C++)
【算法】哈希映射(C/C++)