给定数字N ,任务是将最小数量的开括号和闭括号插入数字N ,以使结果字符串平衡,并且每个数字D都正好在D个匹配括号对中。
例子:
Input: N = 312
Output: (((3))1(2))
Explanation:
Every digit in the number is within exactly in D parenthesis.
There are other possible strings like (((3)))(1)((2)) but the string obtained is the string that can be formed with the minimum number of parenthesis.
Input: N = 111000
Output: (111)000
Explanation:
Every digit in the number is within exactly D parenthesis.
There are other possible strings like (1)(1)(1)000, (11)(1)000 but the string obtained is the string that can be formed with the minimum number of parenthesis.
方法:想法是使用数组来跟踪需要添加的括号的数量。
对于任何数字,只能通过在括号内嵌套数字来添加最小括号。
例如:让N = 321。
- 最初,创建一个空数组A []。
- 给定的数字以数字方式进行迭代。
- 最初,在数组中添加D个开头括号以存储该数字。因此,对于数字3,在数组中添加了3个左括号。
- 在下一次迭代中,该数字可以大于或小于前一个数字。如果下一个数字较小(如上述示例中的2),则将3 – 2 = 1括号括起来。
- 同样,如果下一位数字更大,则将打开括号中的绝对差数。
- 对给定数字N中的所有数字重复上述两个步骤。最后,获得的字符串以最小的括号形成。
下面是上述方法的实现:
# Python program to find the balanced
# parentheses using the given number
# Function to find the balanced
# parentheses using the given number
def balance(m):
# Making the list of the
# given number
m = [int(i) for i in m]
# Empty list to store the
# parentheses
n = []
# Iterating through the
# digits of the number
for i in m:
# Calculating the difference between
# opening and closing braces for the
# digit
if (n.count('(')-n.count(')'))<= i:
# If the next digit is greater,
# then open the brackets
while (n.count('(')-n.count(')')) != i:
n.append('(')
n.append(i)
# Similarly, find the difference
# between opening and closing braces
elif (n.count('(')-n.count(')'))>i:
# If the next digit is smaller,
# then close the brackets
while (n.count('(')-n.count(')'))!= i:
n.append(')')
n.append(i)
# Finally, close the remaining brackets
while (n.count('(')-n.count(')'))!= 0:
n.append(')')
# Returning the string
return ''.join(map(str, n))
# Driver code
if __name__ == "__main__":
N = 312
print(balance(str(N)))
(((3))1(2))
时间复杂度: O(K 2 ) ,其中K是数字N的数字总和。