public ArrayList<String> generateParenthesis(int n) {

    ArrayList<String> result = new ArrayList<String>();

    if (n == 0) {
      return result;
    }

    if (n == 1) {
      result.add("()");
    } else {
      List<String> last = generateParenthesis(n - 1);
      Set<String> curt = new HashSet<String>();
      for (String p : last) {
        for (int i = 0 ; i < p.length() ; i++) {
          StringBuilder sb = new StringBuilder(p);
          sb.insert(i, '(');
          sb.insert(i + 1, ')');
          if (!curt.contains(sb.toString())) {
            curt.add(sb.toString());
          }
        }
      }
      result.addAll(curt);
    }

    return result;
  }