zoukankan      html  css  js  c++  java
  • 蜗牛慢慢爬 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
    
    
  • 相关阅读:
    Mybatis和Hibernate
    SpringMVC运行原理
    HTML中class属性里有多个属性值
    json对象(增加数据)
    Ajax请求
    <url-pattern>里的/和/*
    mysql忘记密码
    Eclipse无法正常连接mysql8.0.20
    a+1和&a+1
    可重入函数与不可重入函数
  • 原文地址:https://www.cnblogs.com/cookielbsc/p/7502164.html
Copyright © 2011-2022 走看看