给定一个由N 个整数组成的数组arr[]和一个整数K ,任务是构造一个满足以下条件的长度为K的二进制字符串:
- 如果可以从数组形成总和为i的子集,则第i个索引处的字符为 ‘ 1′ 。
- 否则,第i个索引处的字符为‘0’ 。
例子:
Input: arr[] = {1, 4}, K = 5
Output: 10011
Explanation:
Character at 1st index can be made by ‘1’ considering the subset {1}.
Character at 4th index can be made by ‘1’ considering the subset {4}.
Character at 5th index can be made by ‘1’ considering the subset {1, 4}.
Input: arr[] = {1, 6, 1}, K = 8
Output: 11000111
方法:这个想法是使用贪心的方法来解决这个问题。以下是步骤:
- 初始化一个 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个位置。
- 从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)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live