22. Generate Parentheses

来源:互联网 发布:网络用语up是什么意思 编辑:程序博客网 时间:2024/05/04 07:33

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> list = new ArrayList<String>();    generateOneByOne("", list, n, n);    return list;}public void generateOneByOne(String sublist, List<String> list, int left, int right){    if(left > right){        return;    }    if(left > 0){        generateOneByOne( sublist + "(" , list, left-1, right);    }    if(right > 0){        generateOneByOne( sublist + ")" , list, left, right-1);    }    if(left == 0 && right == 0){        list.add(sublist);        return;    }}思路是遍历了每一种可能性,排除不符合条件的情况
 
原创粉丝点击