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:

"((()))", "(()())", "(())()", "()(())", "()()()"

import java.util.*;
public class Solution {
    public ArrayList<String> generateParenthesis(int n) {
        ArrayList<String> res = new ArrayList<String>();
        helper("",res,n,0,0);
        return res;
    }
    public void helper (String curr,ArrayList<String> res,int n,int left,int right)
    {
        if(right == n)
        {
            res.add(curr);
        }
        if(left < n)
            helper (curr+"(",res,n,left+1,right);
        if(right < left)
            helper (curr+")",res,n,left,right+1);
    }
}

use the recursive

猜你喜欢

转载自blog.csdn.net/neo233/article/details/80781233