Q:
Implement an algorithm to print all valid (e.g., properly opened and closed) combinations of n-pairs of parentheses.
EXAMPLE:
input: 3 (e.g., 3 pairs of parentheses)
output: ((())), (()()), (())(), ()(()), ()()()
A:DFS.
实现函数为vector<string> generateParens(int n).
1、 vector<string> .left = generateParens(i);
2、 vector<string> .right = generateParens(n-1-i);
3、结果中的一种为 "(" + left[p] + ")" + right[q]
通过遍历,便能够得到所有的情况。
#include <iostream>
#include <vector>
#include <string>
using namespace std;
vector<string> generateParens(int n) {
vector<string> res;
if (n <= 0) {
res.push_back("");
return res;
}
if (n == 1) {
res.push_back("()");
return res;
}
for (int i = 0; i < n; i++) {
vector<string> left = generateParens(i);
vector<string> right = generateParens(n-1-i);
for (int j = 0; j < left.size(); j++) {
for (int p = 0; p < right.size(); p++) {
string cur = "(" + left[j] + ")" + right[p];
res.push_back(cur);
}
}
}
return res;
}
void printRes (vector<string> &res) {
for (int i = 0; i < res.size(); i++) {
cout<<res[i]<<endl;
}
}
int main() {
vector<string> res = generateParens(3);
printRes(res);
return 0;
}