题目链接https://leetcode-cn.com/problems/generate-parentheses/submissions/题目:
数字 n
代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example 1:
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2:
Input: n = 1
Output: ["()"]
思路:
之前两次遇到这个题目,第一次不会,第二次长时间debug之后写出来,这一次很快AC。这大概就算是进步吧!思路是递归搜索,条件是控制左括号一直比右括号多,而且边界的时候返回,就这么简单啦!
代码:
class Solution {
private:
vector<string> answer;
public:
/* left_num represents the number of left brackets */
void search(int n, int left_num, int right_num, int i, string str){
printf("current left_num is %d, right_num is %d, i is %d.\n", left_num, right_num, i);
if(left_num<right_num) return;
if(i==2*n){
if(left_num!=n || right_num!=n) return;
else answer.push_back(str);
return;
}
search(n, left_num+1, right_num, i+1, str+"(");
search(n, left_num, right_num+1, i+1, str+")");
return;
}
vector<string> generateParenthesis(int n) {
search(n,0,0,0,"");
return answer;
}
};