Home AtCoder. 002 Encyclopedia of Parentheses(3)
Post
Cancel

AtCoder. 002 Encyclopedia of Parentheses(3)

[Link] https://AtCoder.jp/contests/typical90/tasks/typical90_b


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
28
29
30
31
32
33
34
35
36
37
38
import java.util.*;
import java.io.*;

public class Main{
  static int n;
  static StringBuilder sb = new StringBuilder();
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    n = sc.nextInt();
    if(n%2 == 1) return;

    char[] charArr = new char[n];
    bfs(charArr, 0, 0, 0);
    System.out.println(sb.toString());
  }

  static void bfs(char[] charArr, int index, int open, int close) {
    if(index == n) {
      sb.append(new String(charArr)).append("\n");
      return;
    }
    if(open < n/2 && close < n/2) {
      charArr[index] = '(';
      open++;
      bfs(charArr, index + 1 , open, close);
      open--;
      if(open > close) {
        charArr[index] = ')';
        close++;
        bfs(charArr, index + 1 , open, close);
        close--;
      }
    } else if(open == n/2) {
      for(int i = index; i < n; i++) charArr[i] = ')';
      bfs(charArr, n, n/2, n/2);
    }
  }
}
This post is licensed under CC BY 4.0 by the author.