📌  相关文章
📜  计算没有连续 1 的二进制字符串的数量

📅  最后修改于: 2021-09-22 10:27:17             🧑  作者: Mango

给定一个正整数 N,计算所有可能的长度为 N 的不同二进制字符串,使得没有连续的 1。

例子:

Input:  N = 2
Output: 3
// The 3 strings are 00, 01, 10

Input: N = 3
Output: 5
// The 5 strings are 000, 001, 010, 100, 101

这个问题可以用动态规划解决。设 a[i] 是长度为 i 且不包含任何两个连续 1 且以 0 结尾的二进制字符串的数量。类似地,设 b[i] 是此类以 1 结尾的字符串的数量。我们可以附加0 或 1 到以 0 结尾的字符串,但我们只能将 0 附加到以 1 结尾的字符串。这产生递归关系:

a[i] = a[i - 1] + b[i - 1]
b[i] = a[i - 1] 

上述循环的基本情况是 a[1] = b[1] = 1。长度为 i 的字符串总数就是 a[i] + b[i]。
以下是上述解决方案的实现。在以下实现中,索引从 0 开始。因此 a[i] 表示输入长度为 i+1 的二进制字符串的数量。类似地,b[i] 表示输入长度为 i+1 的二进制字符串。

C++
// C++ program to count all distinct binary strings
// without two consecutive 1's
#include 
using namespace std;
 
int countStrings(int n)
{
    int a[n], b[n];
    a[0] = b[0] = 1;
    for (int i = 1; i < n; i++)
    {
        a[i] = a[i-1] + b[i-1];
        b[i] = a[i-1];
    }
    return a[n-1] + b[n-1];
}
 
 
// Driver program to test above functions
int main()
{
    cout << countStrings(3) << endl;
    return 0;
}


Java
class Subset_sum
{
    static  int countStrings(int n)
    {
        int a[] = new int [n];
        int b[] = new int [n];
        a[0] = b[0] = 1;
        for (int i = 1; i < n; i++)
        {
            a[i] = a[i-1] + b[i-1];
            b[i] = a[i-1];
        }
        return a[n-1] + b[n-1];
    }
    /* Driver program to test above function */
    public static void main (String args[])
    {
          System.out.println(countStrings(3));
    }
}/* This code is contributed by Rajat Mishra */


Python3
# Python program to count
# all distinct binary strings
# without two consecutive 1's
 
def countStrings(n):
 
    a=[0 for i in range(n)]
    b=[0 for i in range(n)]
    a[0] = b[0] = 1
    for i in range(1,n):
        a[i] = a[i-1] + b[i-1]
        b[i] = a[i-1]
     
    return a[n-1] + b[n-1]
 
# Driver program to test
# above functions
 
print(countStrings(3))
 
# This code is contributed
# by Anant Agarwal.


C#
// C# program to count all distinct binary
// strings without two consecutive 1's
using System;
 
class Subset_sum
{
    static int countStrings(int n)
    {
        int []a = new int [n];
        int []b = new int [n];
        a[0] = b[0] = 1;
        for (int i = 1; i < n; i++)
        {
            a[i] = a[i-1] + b[i-1];
            b[i] = a[i-1];
        }
        return a[n-1] + b[n-1];
    }
     
    // Driver Code
    public static void Main ()
    {
        Console.Write(countStrings(3));
    }
}
 
// This code is contributed by nitin mittal


PHP


Javascript


输出:

5

来源:
course.csail.mit.edu/6.006/oldquizzes/solutions/q2-f2009-sol.pdf
如果我们仔细观察该模式,我们可以观察到,当 n >= 1 时,计数实际上是第 (n+2) 个斐波那契数。斐波那契数是 0、1、1、2、3、5、8 , 13, 21, 34, 55, 89, 141, ….

n = 1, count = 2  = fib(3)
n = 2, count = 3  = fib(4)
n = 3, count = 5  = fib(5)
n = 4, count = 8  = fib(6)
n = 5, count = 13 = fib(7)
................

因此,我们也可以使用此处的方法 5 计算 O(Log n) 时间内的字符串。

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程