• 蜗牛慢慢爬 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
    
    
  • 相关阅读:
    无符号数和有符号数字操作的一些注意事项
    C/C++的基本数据类型
    GoLang字符串比较(二)
    Sphinx使用指南
    GoLang字符串比较(一)
    并发与调度亲和性
    golang scheduler工作窃取
    g0
    如何将markdown转换成微信公众号中支持的html
    goroutine是如何被回收的
  • 原文地址:https://www.cnblogs.com/cookielbsc/p/7502164.html
Copyright © 2020-2023  润新知