给定两个整数N 和 K ,任务是计算生成长度为 N 的二进制字符串的方法的数量,使得 0 在一组大小为 K 的组中总是一起出现。
例子:
Input: N = 3, K = 2
Output : 3
No of binary strings:
111
100
001
Input : N = 4, K = 2
Output : 5
使用动态规划可以轻松解决此问题。令dp[i]为满足条件的长度为i的二进制字符串的数目。
从条件可以推导出:
- dp[i] = 1 对于 1 <= i < k 。
- 同样dp[k] = 2因为长度为 K 的二进制字符串将是一个只有零或只有一个的字符串。
- 现在,如果我们考虑 i > k。如果我们决定第 i个字符为 ‘1’,那么dp[i] = dp[i-1]因为二进制字符串的数量不会改变。但是,如果我们决定第 i个字符为 ‘0’,那么我们要求之前的 k-1 个字符也应为 ‘0’,因此 dp[i] = dp[ik] 。因此 dp[i] 将是这两个值的总和。
因此,
dp[i] = dp[i - 1] + dp[i - k]
下面是上述方法的实现:
C++
// C++ implementation of the above approach
#include
using namespace std;
const int mod = 1000000007;
// Function to return no of ways to build a binary
// string of length N such that 0s always occur
// in groups of size K
int noOfBinaryStrings(int N, int k)
{
int dp[100002];
for (int i = 1; i <= k - 1; i++) {
dp[i] = 1;
}
dp[k] = 2;
for (int i = k + 1; i <= N; i++) {
dp[i] = (dp[i - 1] + dp[i - k]) % mod;
}
return dp[N];
}
// Driver Code
int main()
{
int N = 4;
int K = 2;
cout << noOfBinaryStrings(N, K);
return 0;
}
Java
// Java implementation of the approach
import java.util.*;
class GFG
{
static int mod = 1000000007;
// Function to return no of ways to build a binary
// string of length N such that 0s always occur
// in groups of size K
static int noOfBinaryStrings(int N, int k)
{
int dp[] = new int[100002];
for (int i = 1; i <= k - 1; i++)
{
dp[i] = 1;
}
dp[k] = 2;
for (int i = k + 1; i <= N; i++)
{
dp[i] = (dp[i - 1] + dp[i - k]) % mod;
}
return dp[N];
}
// Driver Code
public static void main(String[] args)
{
int N = 4;
int K = 2;
System.out.println(noOfBinaryStrings(N, K));
}
}
// This code contributed by Rajput-Ji
Python3
# Python3 iimplementation of the
# above approach
mod = 1000000007;
# Function to return no of ways to
# build a binary string of length N
# such that 0s always occur in
# groups of size K
def noOfBinaryStrings(N, k) :
dp = [0] * 100002;
for i in range(1, K) :
dp[i] = 1;
dp[k] = 2;
for i in range(k + 1, N + 1) :
dp[i] = (dp[i - 1] + dp[i - k]) % mod;
return dp[N];
# Driver Code
if __name__ == "__main__" :
N = 4;
K = 2;
print(noOfBinaryStrings(N, K));
# This code is contributed by Ryuga
C#
// C# implementation of the approach
using System;
class GFG
{
static int mod = 1000000007;
// Function to return no of ways to build
// a binary string of length N such that
// 0s always occur in groups of size K
static int noOfBinaryStrings(int N, int k)
{
int []dp = new int[100002];
for (int i = 1; i <= k - 1; i++)
{
dp[i] = 1;
}
dp[k] = 2;
for (int i = k + 1; i <= N; i++)
{
dp[i] = (dp[i - 1] + dp[i - k]) % mod;
}
return dp[N];
}
// Driver Code
public static void Main()
{
int N = 4;
int K = 2;
Console.WriteLine(noOfBinaryStrings(N, K));
}
}
/* This code contributed by PrinciRaj1992 */
PHP
Javascript
输出:
5
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。