22. Generate Parentheses

题目描述

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, givenn= 3, a solution set is:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

解题方法

    public List<String> generateParenthesis(int n){
        List<String> lists = new LinkedList<>();
        if( n <= 0){
            return lists;
        }
        helper(n, "", 0, 0, lists);
        return lists;
    }

    private void helper(int n, String prefix, int open, int close, List<String> lists){
        if(prefix.length() == n << 1){
            lists.add(prefix);
            return;
        }
        if(open < n){
            helper(n, prefix + "(", open + 1, close, lists);
        }
        if(close < open){
            helper(n, prefix + ")", open, close + 1, lists);
        }
    }

results matching ""

    No results matching ""