leetcode22_Generate Parentheses
一.題目描述
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
相關文章
- Remove Invalid Parentheses[難]REM
- 22. Generate Parentheses (recursion algorithm)Go
- Leetcode 22 Generate ParenthesesLeetCode
- Leetcode Valid ParenthesesLeetCode
- 演算法Valid Parentheses演算法
- Leetcode-Generate ParenthesesLeetCode
- Generate Parentheses leetcode javaLeetCodeJava
- Leetcode 20 Valid ParenthesesLeetCode
- Leetcode-Valid ParenthesesLeetCode
- 【Python】 Missing parentheses in call to 'print'Python
- Valid Parentheses leetcode javaLeetCodeJava
- Leetcode 32 Longest Valid ParenthesesLeetCode
- LeetCode-Remove Invalid ParenthesesLeetCodeREM
- Leetcode-Longest Valid ParenthesesLeetCode
- [LeetCode] Generate Parentheses 生成括號LeetCode
- leetcode 之 Longest Valid ParenthesesLeetCode
- Longest Valid Parentheses leetcode javaLeetCodeJava
- [LeetCode] 32. Longest Valid ParenthesesLeetCode
- Leetcode - 022. Generate ParenthesesLeetCode
- leetcode32_Longest Valid ParenthesesLeetCode
- LeetCode-Different Ways to Add ParenthesesLeetCode
- [LeetCode] Valid Parentheses 驗證括號LeetCode
- LeetCode Generate Parentheses(022)解法總結LeetCode
- 【LeetCode從零單排】No22.Generate ParenthesesLeetCode
- LeetCode Valid Parentheses(020)解法總結LeetCode
- [LeetCode] Longest Valid Parentheses 最長有效括號LeetCode
- Leetcode 20 有效的括號valid-parentheses(棧)LeetCode
- 【leetcode】22. Generate Parentheses 合法括號串的所有組合LeetCode
- LeetCode解題報告 241. Different Ways to Add Parentheses [medium]LeetCode
- LeetCode 之 JavaScript 解答第20題 —— 有效的括號(Valid Parentheses)LeetCodeJavaScript
- 【leetcode】32. Longest Valid Parentheses 最長的有效匹配括號子串長度LeetCode