leetcode22_Generate Parentheses

橘子oly發表於2016-10-19

一.題目描述

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]


二.程式碼編寫

思想:像是對樹進行深度優先遍歷DFS,遍歷的思想就是能加左括號的時候就加(左括號沒用完時),不能加左括號時如果能加右括號就加右括號(只要當前左括號個數大於右括號就能加),當左右括號都用完的時候將該字串加到輸出陣列,並對字串從後往前找第一個可以被替換成右括號的左括號替換成右括號,再重複這個過程。

實現程式碼如下:

class Solution(object):
    def generateParenthesis(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        re_str = '('
        re_str_list = []
        i = 1  # left Parentheses used
        j = 0  # right Parentheses usedd
        while i<=n or j<=n:
            if i<n:
                # add left Parentheses if can
                re_str += '('
                i += 1
            elif i>j: # when left Parentheses is run out, add right Parentheses if can
                re_str += ')'
                j += 1
            elif len(re_str) == 2*n:
                re_str_list.append(re_str)   # add to output list
                index=re_str.rfind('(')   #backtracking 
                while index != -1:  # -1 stands for not found
                    if 2*re_str[:index].count(')')<index:
                        re_str = re_str[:index]+')'   # change left Parentheses to right
                        i = re_str.count('(')
                        j = index - i + 1
                        break
                    else:
                        index=re_str[:index].rfind('(')
                if index == -1:
                    return re_str_list
        return re_str_list


相關文章