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:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]
public class Solution {
    //f("", 0, 0, 2) 
    //   | f("(", 1, 0, 2)
    //      | f("((", 2, 0, 2)
    //          | f("(()", 2, 1, 2)
    //              | f("(())", 2, 2, 2)
    //                  | "(())".length == 2*2 -> add -> return;
    //      | f("()", 1, 1, 2)
    //          | f("()(", 2, 1, 2)
    //              | f("()()", 2, 2, 2)
    //                  | "()()".length == 2*2 -> add -> return; 
    public List<String> generateParenthesis(int n) {
        List<String> list = new ArrayList<String> (); 
        backtrack(list, "", 0, 0, n);
        return list;
    }
    
    //open: left parenthese
    //close: right parenthese
    //max: number of parenthese pairs
    public void backtrack(List<String> list, String str, int open, int close, int max) {
        if (str.length() == max*2) {
            list.add(str);
            return; 
        }
        //open < max -> gaurantee "max" number of () 
        if (open < max) {
            backtrack(list, str+"(", open+1, close, max);
        }
        //close < open -> gaurantee parenthesis symmetry
        if (close < open) {
            backtrack(list, str+")", open, close+1, max);
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s