通过分析生成的括号全排列,要求在排列生成的过程中右括号的数量小于等于左括号的数量。
基于上述想法,我们在回溯的过程中设置两个指针left和right;
代码如下:
class Solution:
def generateParenthesis(self, n):
ans = []
def back(tmp,left,right):
if len(tmp) == 2 * n:
ans.append(tmp)
return
if left < n:
back(tmp + '(', left + 1, right)
if right < left:
back(tmp + ')', left, right + 1)
back('',left = 0,right = 0)
return ans
下面是时间复杂度较高的:回溯的全排列+去重(剪枝)
class Solution:
def generateParenthesis(self, n):
#首先生成数组
nums = '(' * n + ')' * n
# print(nums)
# for i in range(len(nums)):
# print(nums[i])
result = []
count1 = 0
count2 = 0
size = len(nums)
used = [False] * n * 2
def back(nums,tmp):
if len(tmp) == size:
result.append(tmp)
# print(result)
# count1 = 0
# count2 = 0
return#返回时候说明执行完毕
for i in range(len(nums)):
# print(used[i])
if not used[i]:
# print("####")
# print(i)
# print("*****")
# print(nums[i])
if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]:
continue
count11 = (tmp + nums[i]).count('(')
count22 = (tmp + nums[i]).count(')')
# print(count11)
# print(count22)
if count11 < count22:
continue
used[i] = True
back(nums,tmp + nums[i])#
used[i] = False
back(nums,'')
return result