📌  相关文章
📜  根据给定条件从数组构造一个 K 长度的二进制字符串

📅  最后修改于: 2021-10-26 05:54:38             🧑  作者: Mango

给定一个由N 个整数组成的数组arr[]和一个整数K ,任务是构造一个满足以下条件的长度为K的二进制字符串:

  1. 如果可以从数组形成总和为i的子集,则i索引处的字符为 ‘ 1′
  2. 否则,第i索引处的字符为‘0’

例子:

方法:这个想法是使用贪心的方法来解决这个问题。以下是步骤:

  • 初始化一个 bitset,比如bit[] ,大小为10 5 + 5并设置bit[0] = 1。
  • 通过阵列以及对于每个阵列元素ARR [I],更新比特作为比特遍历| =位<< ARR [I]具有P如果p可作为子集之和来获得
  • i迭代中bit[i]存储初始总和,在执行bit << arr[i] 后,所有位都移动了arr[i] 。因此,位p变为p + arr[i]。
  • 最后,| (bit << arr[i])合并这两种情况,是否考虑第i位置。
  • 1K迭代并将每个值bit[i]打印为所需的二进制字符串。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// To construct the
// required binary string
bitset<100003> bit;
 
// Function to construct binary string
// according to the given conditions
void constructBinaryString(int arr[],
                           int N, int K)
{
    // Initialize with 1
    bit[0] = 1;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // To check if the i-th integer
        // needs to be considered or not
        bit |= bit << arr[i];
    }
 
    // Print the binary string
    for (int i = 1; i <= K; i++) {
        cout << bit[i];
    }
}
 
// Driver Code
int main()
{
    // Given array
    int arr[] = { 1, 6, 1 };
 
    // Size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Given K
    int K = 8;
 
    constructBinaryString(arr, N, K);
}


Python3
# Python program for the above approach
 
# To construct the
# required binary string
#bit = [0]*100003
 
# Function to construct binary string
# according to the given conditions
def constructBinaryString(arr,N, K):
     
    # Initialize with 1
    bit = 1
     
    # Traverse the array
    for i in range(0, N):
       
        # To check if the i-th eger
        # needs to be considered or not
        bit |= bit << arr[i]
     
    # Print the binary string
    #for i in range(1,K):
    #    print(bit[i])
    bit = bin(bit).replace("0b", "")
    print(bit[1:K + 1])
     
# Driver Code
# Given array
arr = [1, 6, 1]
 
# Size of the array
N = len(arr)
 
# Given K
K = 8
 
constructBinaryString(arr, N, K)
 
# This code is contributed by shubhamsingh10


输出:
11000111

时间复杂度: O(N)
辅助空间: O(N)

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