Loading

[LeetCode] 22. Generate Parentheses(括号生成器)

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)
        }
    }
}
posted @ 2020-10-28 09:13  Zhongju.copy()  阅读(95)  评论(0编辑  收藏  举报