Generate Parentheses(组合,回溯)
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
暴力思路:其实就是组合,n=3,则有6个位置,每个位置可以插入'(',或者')',当n=3时,就有64中可能,只需对每一种可能作必要的筛选即可。
代码:
class Solution { private: char parenthesis[2]; vector<string> res; int num; public: void dfs(int dep,string temp){ if(dep==num){ stack<char> s; for (int i=0;i<temp.size();++i) { if(s.empty()) s.push(temp[i]); else if(!s.empty()&&temp[i]==')'){ if(s.top()=='(') s.pop(); }else{ s.push(temp[i]); } } if(!s.empty()) return; res.push_back(temp); return; } for (int i=0;i<2;++i) { temp.push_back(parenthesis[i]); dfs(dep+1,temp); temp.pop_back(); } return; } vector<string> generateParenthesis(int n) { parenthesis[0]='('; parenthesis[1]=')'; num=n*2; string temp=""; dfs(0,temp); return res; } };