[leetcode] 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:

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

思路:这道题要是不分析规律的话,很难想出答案本题的规律是假如left的个数大于right的个数,就可以添加')';假如left的个数小于n,就可以添加'('。利用递归,先给出递归结束条件,然后不断深入。

代码:

public class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> list=new ArrayList<String>();
        if(n<=0)return list;
        generate(0, list, 2*n, "", 0, 0);
        System.out.println(list);
        return list;
    }
    public void generate(int index,List<String> list,int size,String str,int left,int right)
    {
        if(index==size)
        {
            list.add(str);
            return;
        }
        index++;
        if(left>right)
            generate(index, list, size, str+')', left, right+1);
        if(left<size/2)
            generate(index, list, size, str+'(', left+1, right);
    }
}

 

你可能感兴趣的:(LeetCode)