给定一个二进制字符串S ,任务是打印所有不同的十进制数字,这些数字可以通过生成二进制字符串的所有排列来获得。
例子:
Input: S = “110”
Output: {3, 5, 6}
Explanation:
All possible permutations are {“110”, “101”, “110”, “101”, “011”, “011”}.
Equivalent decimal numbers of these binary strings are {6, 5, 6, 5, 3, 3} respectively.
Therefore, the distinct decimal numbers obtained are {3, 5, 6}.
Input: S = “1010”
Output: {3, 5, 6, 9, 10, 12}
方法:可以使用Set解决问题。请按照以下步骤解决问题:
- 将给定的字符串转换为字符列表。
- 使用内置的Python函数itertools替换此列表。 permutations()。
- 初始化一个空字符串s。
- 遍历排列列表,并对每个排列执行以下步骤:
- 遍历字符并将它们添加到字符串。
- 将此二进制字符串转换为等效的小数。
- 将获得的当前十进制值插入到集合中。
- 最后,打印出集合中存在的数字。
下面是上述方法的实现:
Python3
# Python3 program for the above approach
from itertools import permutations
# Function to convert binary
# string to equivalent decimal
def binToDec(n):
num = n
dec_value = 0
# Initializing base
# value to 1, i.e 2 ^ 0
base1 = 1
len1 = len(num)
for i in range(len1 - 1, -1, -1):
if (num[i] == '1'):
dec_value += base1
base1 = base1 * 2
# Return the resultant
# decimal number
return dec_value
# Function to print all distinct
# decimals represented by the
# all permutations of the string
def printDecimal(permute):
# Set to store distinct
# decimal representations
allDecimals = set()
# Iterate over all permuations
for i in permute:
# Initilalize an empty string
s = ""
# Traverse the list
for j in i:
# Add each element
# to the string
s += j
# Convert the current binary
# representation to decimal
result = binToDec(s)
# Add the current decimal
# value into the set
allDecimals.add(result)
# Print the distinct decimals
print(allDecimals)
# Utility function to print all
# distinct decimal representations
# of all permutations of string
def totalPermutations(string):
# Convert string to list
lis = list(string)
# Built in method to store all
# the permuations of the list
permutelist = permutations(lis)
printDecimal(permutelist)
# Given binary string
binarystring = '1010'
# Function call to print all distinct
# decimal values represented by all
# permutations of the given string
totalPermutations(binarystring)
输出:
{3, 5, 6, 9, 10, 12}
时间复杂度: O(N * N!)
辅助空间: O(N * N!)