蜗牛慢慢爬 LeetCode 22. Generate Parentheses [Difficulty: Medium]

时间:2023-03-09 07:58:37
蜗牛慢慢爬 LeetCode 22. Generate Parentheses [Difficulty: Medium]

题目

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:

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

翻译

生成所有的括号匹配

Hints

Related Topics: String, Backtracking

利用回溯法

代码

Java

class Solution {
public List<String> generateParenthesis(int n) {
List<String> list = new List<String>();
backtrack("", list, n, n);
return list;
}
public void backtrack(String s, List<String> list, int left, int right){
if(left > right){
return;
}
if(left > 0){
backtrack(s+"(", list, left-1, right);
}
if(right > 0){
backtrack(s+")", list, left, right-1);
}
if(left==0 && right==0){
list.add(s);
return;
}
}
}

Python

class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
def backtrack(l, s, left, right, maxlen):
if len(s)==maxlen*2:
l.append(s)
return
if left < maxlen:
backtrack(l, s+'(', left+1, right, maxlen)
if right < left:
backtrack(l, s+')', left, right+1, maxlen) result = []
backtrack(result, '', 0, 0, n)
return result