Monday, February 25, 2013

[LeetCode] Generate Parentheses

Thought:
Use Recursion, 
if right = left = n, we update the result.
if right = left < n, we add "(",
if right < left = n, we add ")",
if right < left < n, we could add "(" or ")".

Code:
public class Solution {
    public ArrayList<String> generateParenthesis(int n) {
       
        ArrayList<String> result = new ArrayList<String>();
        char[] temp = new char[2 * n];
       
        build(result, 0, 0, n, temp);
        
        return result;
    }
    public void build(ArrayList<String> result, int left, int right, int n, char[] temp){
        if(left == right && left == n){
            result.add(new String(temp));
            return;
        }else{// some kind of DFS
            if(left < n){
                temp[left + right] = '(';
                build(result, left + 1, right, n, temp);
            }
            if(left > right){
                temp[left + right] = ')';
                build(result, left, right + 1, n, temp);               
            }
        }
    }
}

No comments:

Post a Comment