题解 | #括号生成#
括号生成
https://www.nowcoder.com/practice/c9addb265cdf4cdd92c092c655d164ca
struct MyTreeNode{ MyTreeNode(string num){ val = num; }; string val; MyTreeNode *left=nullptr, *right=nullptr; }; class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param n int整型 * @return string字符串vector */ vector<string> generateParenthesis(int n) { // write code here int left_count = 0; int right_count = 0; int level = 1; string str = ""; vector<string> res; dfs(left_count, right_count,level,n,str,res); return res; } void dfs(int left_count, int right_count, int level, int n, string str, vector<string> &res){ if(level > 2*n){ res.push_back(str); return; }else{ if(left_count > right_count){ dfs(left_count, right_count+1,level+1,n,str+")",res); } if(left_count < n){ dfs(left_count+1, right_count,level+1,n,str+"(",res); } } } };