给定一个正整数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)时间中的字符串。