括号的全排列问题2

include<bits/stdc++.h>

void generate(string current, int left, int right, int n, vector& result) {
// 终止条件:序列长度达到2n
if (current.length() == 2 * n) {
result.push_back(current);
return;
}

// 左括号数量小于n时,可以添加左括号
if (left < n) {
    generate(current + "(", left + 1, right, n, result);
}

// 右括号数量小于左括号时,可以添加右括号(保证有效性)
if (right < left) {
    generate(current + ")", left, right + 1, n, result);
}

}

int main() {
int n;
cout << "请输入n的值:";
cin >> n;

vector<string> result;
generate("", 0, 0, n, result);

// 输出所有有效括号组合
cout << "共有" << result.size() << "种有效组合:" << endl;
for (const string& s : result) {
    cout << s << endl;
}

system("pause");
return 0;

}

这里用到了很多函数模板中的函数,回头好好理解一下即可
总之,挺麻烦的。

posted @ 2025-08-01 20:47  暗神酱  阅读(4)  评论(0)    收藏  举报