📜  具有二进制等价的给定数组的子序列计数

📅  最后修改于: 2021-09-07 02:11:54             🧑  作者: Mango

给定一个由N 个整数组成的数组 arr[] ,任务是找到具有 Binary Equivalence的不同子序列的总数。

例子:

方法:思路是求表示数组最大元素所需的总位数。按照以下步骤解决这个问题:

  1. 找到最大元素和最大元素的二进制表示的长度。
  2. 在二进制表示的其他元素前面附加0 ,使每个元素的位数等于最大位数。
  3. 查找给定数组的所有子序列。
  4. 找出具有 Binary Equivalence的子序列的总数。
  5. 如果总数的长度小于最大数的长度,则将总数转换为二进制并附加0,使两者的长度相等。

下面是上述方法的实现:

Python3
# Python program for the above approach
import itertools
 
# Function to find the number of
# subsequences having Binary Equivalence
def numberOfSubsequence(arr):
 
    # Find the maximum array element
    Max_element = max(arr)
 
    # Convert the maximum element
    # to its binary equivalent
    Max_Binary = "{0:b}".format(int(
        Max_element))
 
    # Dictionary to store the count of
    # set and unset bits of all array elements
    Dic = {}
 
    for i in arr:
        Str = "{0:b}".format(int(i))
 
        if len(Str) <= len(Max_Binary):
            diff = len(Max_Binary)-len(Str)
 
            # Add the extra zeros before all
            # the elements which have length
            # smaller than the maximum element
            Str = ('0'*diff)+Str
 
        zeros = Str.count('0')
        ones = Str.count('1')
 
        # Fill the dictionary with number
        # of 0's and 1's
        Dic[int(i)] = [zeros, ones]
 
    all_combinations = []
 
    # Find all the combination
    for r in range(len(arr)+1):
 
        comb = itertools.combinations(arr, r)
        comlist = list(comb)
        all_combinations += comlist
    count = 0
 
    # Find all the combinations where
    # sum_of_zeros == sum_of_ones
    for i in all_combinations[1:]:
        sum0 = 0
        sum1 = 0
        for j in i:
            sum0 += Dic[j][0]
            sum1 += Dic[j][1]
 
        # Count the total combinations
        # where sum_of_zeros = sum_of_ones
        if sum0 == sum1:
            count += 1
 
    # Convert the count number to its
    # binary equivalent
    Str = "{0:b}".format(int(count))
    if len(Str) <= len(Max_Binary):
        diff = len(Max_Binary)-len(Str)
 
        # Append leading zeroes to
        # the answer if its length is
        # smaller than the maximum element
        Str = ('0'*diff) + Str
 
    # Print the result
    print(Str)
 
 
# Driver Code
 
# Give array arr[]
arr = [5, 7, 9, 12]
 
# Function Call
numberOfSubsequence(arr)


输出:
0111

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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live