22. Generate Parentheses

来源:互联网 发布:telnet查端口linux 编辑:程序博客网 时间:2024/06/10 02:53

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 class Solution {    public List<String> generateParenthesis(int n) {     List<String> res = new ArrayList<>();     helper(res, new StringBuilder(), 0, 0, n);     return res;}    private void helper(List<String> res, StringBuilder sb, int open, int close, int n) {        if (open == n && close == n) {            res.add(sb.toString());            return;        }        if(open < n) {            helper(res, sb.append("("), open+1, close, n);            sb.setLength(sb.length()-1);        }         if (close < open) {            helper(res, sb.append(")"), open, close+1, n);            sb.setLength(sb.length()-1);        }    }}
原创粉丝点击