Leetcode算法——22、生成括号字符串

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/HappyRocking/article/details/83271151

给定整数n,要求输出 n 对左右括号的所有可能的有效组合。

示例:

输入:n = 3
输出:
[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

思路

为了保证括号字符串是有效的,需要满足两个条件:

  • 左括号必须有同样类型的右括号相匹配
  • 右括号匹配顺序必须和左括号相对应

详情可以参考Leetcode算法——20、判断有效括号

可以使用递归法,来保证这两个条件,步骤如下:

1、起始有 n 个左括号和 n 个右括号需要拼接到字符串中。

2、先将结果字符串初始化为空。

3、每次递归时,选择其中一种括号,拼接到结果字符串的最右边。分为两种情况:

  • 如果剩余左括号和右括号的数量相等,那么下一步只能放左括号
  • 如果剩余右括号多于左括号,那么既可以放左括号,又可以放右括号

不可能出现左括号多于右括号的情况。

4、直至没有剩余括号为止。

python实现

def generateParenthesis(n):
    """
    :type n: int
    :rtype: List[str]
    递归法。
    """
    
    def fun_rec(left_count, right_count):
        '''
        将left_count个左括号和right_count右括号进行有效组合
        '''
        if left_count == 0 and right_count == 0:
            return ['']
        if left_count == 0:
            return [''.join([')'] * right_count)]
        if right_count == 0:
            return [''.join([')'] * right_count)]
        if left_count == right_count: # 左右数量相等时,只能先放左括号
            remain_list = fun_rec(left_count - 1, right_count)
            return ['(' + x for x in remain_list]
        else: # 左括号少于右括号(不可能大于),则左右括号都可以放
            remain_list = fun_rec(left_count - 1, right_count)
            l1 = ['(' + x for x in remain_list]
            remain_list = fun_rec(left_count, right_count - 1)
            l2 = [')' + x for x in remain_list]
            return l1 + l2
        
    return fun_rec(n, n)

if '__main__' == __name__:
    n = 3
    print(generateParenthesis(n))

猜你喜欢

转载自blog.csdn.net/HappyRocking/article/details/83271151