427. 生成括号
题目:
描述
给定 n 对括号,请写一个函数以将其生成新的括号组合,并返回所有组合结果。
您在真实的面试中是否遇到过这个题? 是
样例
给定 n = 3
, 可生成的组合如下:
"((()))", "(()())", "(())()", "()(())", "()()()"
题目链接:
https://www.lintcode.com/problem/generate-parentheses/description
解题思路:本质上就是遍历可能的所有情况。用dfs遍历,决策就是每次在满足条件的情况下分别添加 ' ( ' 和 ' ) '进入下一层,到递归底层时即得到一种组合,加入答案数组即可。注意: ' ( ' 和 ' ) '个数要满足小于n时才添加并进入下一层, ' ) '的添加还要满足当前 ' ) '个数小于' ( '的条件,才能添加并进入下一层。
代码如下:
#include <cstdio>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
/**
* @param n: n pairs
* @return: All combinations of well-formed parentheses
*/
vector <string> ans;
void dfs(int lf, int rt, int n, string str){
if(lf == n && rt == n){
ans.push_back(str);
}
if(lf < n){
dfs(lf + 1, rt, n, str + '(');
}
if(lf > rt && rt < n){
dfs(lf, rt + 1,n , str + ')');
}
return;
}
vector<string> generateParenthesis(int n) {
// write your code here
dfs(0,0,n,"");
return ans;
}
};
int main(){
int n;
scanf("%d",&n);
Solution so;
vector <string> ans = so.generateParenthesis(n);
for(int i = 0;i < ans.size(); i++){
cout << ans[i] << endl;
}
return 0;
}