n,代表括號對數。這段程式碼使用了遞迴和 lambda 函數來實現深度優先搜索(DFS)。
ios::sync_with_stdio(false) 和 cin.tie(0)**:cin 和 cout 的輸入輸出操作,適用於競賽編程。dfs**:lhs 和 rhs 分別表示左括號和右括號的數量。lhs < rhs 或 lhs > n 時,返回。lhs + rhs == 2 * n 時,表示已經生成了一個有效的括號組合,輸出結果。s**:_ 初始化字串 s,長度為 2 * n。
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
while (cin >> n) {
auto dfs = [&](auto self, string& s, int lhs, int rhs) -> void {
if (lhs < rhs || lhs > n) {
return;
}
if (lhs + rhs == 2 * n) {
cout << s << "\n";
return;
}
s[lhs + rhs] = '(';
self(self, s, lhs + 1, rhs);
s[lhs + rhs] = ')';
self(self, s, lhs, rhs + 1);
};
string s(2 * n, '_');
dfs(dfs, s, 0, 0);
cout << "\n";
}
return 0;
}
ios::sync_with_stdio(false) 和 cin.tie(0)**:dfs**:s**:_ 初始化字串 s,長度為 2 * n。