Thursday, July 3, 2014

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:

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

[Thouthts]:结果string的长度肯定是一样的,是2*n。 对于这个string的每一个位置该是左括号还是右括号,只要比较前面左右括号的数量就可以。
public class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<String>();
        char[] temp = new char[n*2];
        genProcess(n, n, 0, temp, res);
        return res;
    }
    
    public void genProcess(int left, int right, int index, char[] temp, List<String> res){
        if(left==0 && right==0){
            res.add(new String(temp));
            return;
        }
        if(left>0){
            temp[index]='(';
            genProcess(left-1, right, index+1, temp, res);
        }
        if(right>left){
            temp[index]=')';
            genProcess(left,right-1,index+1, temp, res);
        }
    }
}

No comments:

Post a Comment