Generate Parentheses

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

之前在 Parentheses总结 讲过这道题目,用回溯法解决,想看更多类似的题目可以参考上面那篇文章。代码如下:
public class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> list = new ArrayList<String>();
        int left = n;
        int right = n;
        generateP(2 * n, left, right, "", list);
        return list;
    }
    public void generateP(int n, int left, int right, String s, List<String> list) {
        if(s.length() == n) list.add(s);
        if(left > 0) generateP(n, left - 1, right, s + '(', list);
        if(right > left) generateP(n, left, right - 1, s + ')', list);
    }
}

你可能感兴趣的:(java,面试,回溯法)