[LeetCode] 22. Generate Parentheses(括号生成器)
-
Difficulty: Medium
-
Related Topics: String, Backtracking
Description
Given n
pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
给 n
对括号,写一个函数生成所有有效的括号对。
Examples
Example 1
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2
Input: n = 1
Output: ["()"]
Constraints
1 <= n <= 8
Solution
在回溯类的题目中,此题属于排列树。考虑到本题要求括号对是有效的,自然一开始往里添加的时候,就要先添加左括号,然后如果右括号数量不够,尝试在其中添加右括号,代码如下:
class Solution {
private val result = arrayListOf<String>()
fun generateParenthesis(n: Int): List<String> {
backtrack("", 0, 0, n)
return result
}
private fun backtrack(cur: String, left: Int, right: Int, total: Int) {
if (cur.length == total * 2) {
result.add(cur)
return
}
if (left < total) {
backtrack("$cur(", left + 1, right, total)
}
if (right < left) {
backtrack("$cur)", left, right + 1, total)
}
}
}