All possible combinations of given 'n' parenthesis


Print all possible combination of given n parenthesis. Eg: if n=2 then all possible combinations are: (n stands for number of parenthesis pair open-close)

{}{}
{{}}


Possible solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class CurlyBraceCombination {
  public static void main(String[] args) {
    int n = 3;
    String forOne = "{}";
    Set allCombos = new LinkedHashSet();
    allCombos.add(forOne);
    for (int i = 1; i < n; i++) {
      Set newCombos = new LinkedHashSet();
      for (Iterator iterator = allCombos.iterator(); iterator.hasNext();) {
        String braceCombo = iterator.next();
        newCombos.add("{}" + braceCombo);
        newCombos.add(braceCombo + "{}");
        newCombos.add("{" + braceCombo + "}");
      }
      allCombos.clear();
      allCombos.addAll(newCombos);
    }
    System.out.println(allCombos);
  }
}

0 comments:

Post a Comment