9/14/2012

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


Idea: 
Keep track of the number of open and close brackets. If there are more open brackets than close ones and the number of open ones has not reached n, then for the next char we have two choices: add a open bracket / add a close bracket. The recursion ends when the number of close brackets reaches n.
 

public class Solution {
    ArrayList<String> result;
    public ArrayList<String> generateParenthesis(int n) {
        // Start typing your Java solution below
        // DO NOT write main() function
        result = new ArrayList<String>();
        if (n<1) return result;
        addBrackets(new String(""), n, 0, 0);
        return result;
    }
    
    private void addBrackets(String str, int target, int open, int close) {
        if (close == target) {
            result.add(str);
        }
        else {
            if (open > close) {
                addBrackets(str + ")", target, open, close + 1);
            }
            if (open < target) {
                addBrackets(str + "(", target, open + 1, close);                
            }
        }
    }
}

No comments:

Post a Comment