ホーム AtCoder. 002 括弧列の図鑑 (3)
記事
キャンセル

AtCoder. 002 括弧列の図鑑 (3)

括弧列を左から順に作ります。どの接頭辞でも、閉じ括弧の数が開き括弧の数を超えてはいけません。そうなると、その後に何を追加しても正しい括弧列にはできません。また、長さ N の正しい括弧列には、開き括弧がちょうど N/2 個含まれます。

したがって、開き括弧を N/2 個より少なく使っている場合に ( を追加し、close < open の場合に限って ) を追加します。接頭辞で両者の数が等しくても、その後に開き括弧を追加できるため問題ありません。長さが N に達した時点で、これらの規則から列全体が正しい括弧列であることが保証されるので出力します。( を ) より先に試すため、正しい括弧列は辞書順に生成されます。N が奇数の場合、最後に両者の数が等しくなることはないため、何も出力されません。

接頭辞のバランスに関する不変条件は 0 <= close <= open <= N/2 です。各結果は一度だけ生成され、時間計算量は出力全体のサイズに比例します。再帰呼び出しと現在の列に必要な作業領域は O(N) であり、バッファに保存する出力領域は別途必要です。

問題リンク

Java

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import java.io.BufferedInputStream;
import java.io.IOException;

public class Main {
    private static int n;
    private static final StringBuilder current = new StringBuilder();
    private static final StringBuilder output = new StringBuilder();

    public static void main(String[] args) throws IOException {
        FastScanner input = new FastScanner();
        n = input.nextInt();
        generate(0, 0);
        System.out.print(output);
    }

    private static void generate(int open, int close) {
        if (current.length() == n) {
            if (open == close) {
                output.append(current).append('\n');
            }
            return;
        }

        if (open < n / 2) {
            current.append('(');
            generate(open + 1, close);
            current.setLength(current.length() - 1);
        }
        if (close < open) {
            current.append(')');
            generate(open, close + 1);
            current.setLength(current.length() - 1);
        }
    }

    private static final class FastScanner {
        private final BufferedInputStream input = new BufferedInputStream(System.in);

        int nextInt() throws IOException {
            int value = 0;
            int c;
            do {
                c = input.read();
            } while (c <= ' ' && c != -1);
            while (c > ' ') {
                value = value * 10 + c - '0';
                c = input.read();
            }
            return value;
        }
    }
}
この記事は著者により CC BY 4.0 ライセンスで公開されています。