美文网首页
String:Generate Parentheses

String:Generate Parentheses

作者: 敲一手烂代码 | 来源:发表于2016-06-07 13:48 被阅读11次

    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:
    [
    "((()))",
    "(()())",
    "(())()",
    "()(())",
    "()()()"
    ]

    public List<String> generateParenthesis(int n) {
            List<String> aryList = new ArrayList<String>();
            getString(aryList, "", 0, 0, n);
            return aryList;
        }
        
        private void getString(List<String> list,String str,int open,int close,int max) {
            if (str.length()==2*max) {
                list.add(str);
                return;
            }
            if (open<max) {
                getString(list, str+"(", open+1, close, max);
            }
            if (close<open) {
                getString(list, str+")", open, close+1, max);
            }
            
        }
    

    相关文章

      网友评论

          本文标题:String:Generate Parentheses

          本文链接:https://www.haomeiwen.com/subject/irbddttx.html