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

📅  最后修改于: 2021-05-25 10:17:57             🧑  作者: Mango

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

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

例子:

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

  • 初始化一个大小为10 5 + 5的集,例如bit [] ,并将bit [0] = 1设置为1。
  • 遍历数组,对于每个数组元素arr [i]如果可以将p作为子集总和获得,则将更新为位| =位<< << arr [i]以具有p
  • i迭代中位[i]存储初始总和,并且在执行<< << arr [i]之后,所有位均移位arr [i] 。因此,位p变为p + arr [i]。
  • 最后一点| (bit << arr [i])合并这两种情况,无论是否考虑第i位置。
  • 1迭代到K,然后将每个值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)