解法一、DFS
🔹 傳遞參考
傳遞參考 string& s
而不是傳遞整個字串 string s
避免不必要的字串複製
✅ 完整代碼
評分結果(參考) : AC (0.2s, 324KB)
#include <bits/stdc++.h>
using namespace std;
int n;
void dfs(int left, int right, string& s){
    if(left+right == 2*n){
        cout << s << "\n";
        return;
    }
    
    if(left < n){
        s[left+right] = '(';
        dfs(left+1, right, s);
    }
    if(right < left){
        s[left+right] = ')';
        dfs(left, right+1, s);
    }
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    
    while(cin >> n){
        string str(2*n, '_');
        dfs(0, 0, str);
        cout << "\n";
    }
    return 0;
}