Generate all combination of parenthesis

By | January 23, 2016
Share the joy
  •  
  •  
  •  
  •  
  •  
  •  

Given a number of pair parenthesis. Generate all combinations. For example n = 2, then should return ArrayList<String> = [“(())”, “()()”];

The solution is like below.

public static ArrayList<String> generateParenthesis(int n) {
    // Write your code here
    ArrayList<String> list = new ArrayList<String>();
    parenthesisHelper(0, 0, n, list, "");
    return list;
}

public static void parenthesisHelper(int open, int close, int pair, ArrayList<String> list, String ans) {
    if (close == pair) {
        list.add(ans);
        return;
    }
    if (open < pair) {
        parenthesisHelper(open + 1, close, pair, list, ans + "(");
    }
    if (close < open) {
        parenthesisHelper(open, close + 1, pair, list, ans + ")");
    }
}

This is a very beautiful recursion. Recursion rule is that number of open parenthesis should not be greater than pair number, number of close parenthesis shouldn’t be greater than number of open parenthesis.

my code on github: link