zoukankan      html  css  js  c++  java
  • [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)
            }
        }
    }
    
  • 相关阅读:
    C语言寒假大作战01
    C语言I作业12—学期总结
    C语言I博客作业11
    C语言I博客作业10
    非数值数据的编码方式
    定点数
    C语言||作业01
    C语言寒假大作战04
    C语言寒假大作战03
    C语言寒假大作战02
  • 原文地址:https://www.cnblogs.com/zhongju/p/13889102.html
Copyright © 2011-2022 走看看