leetcode 22. Generate Parentheses

来源:互联网 发布:linux path环境变量 编辑:程序博客网 时间:2024/05/01 01:51

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:

"((()))", "(()())", "(())()", "()(())", "()()()"



 class Solution { void do_once(set<string>&candi) { set<string>newcandi; set<string>hist; for (set<string>::iterator it = candi.begin(); it != candi.end(); it++) { string str = *it; for (int j = 0; j <= str.length(); j++) { string s = str; s.insert(s.begin() + j, '('); if (hist.find(s) == hist.end()) { hist.insert(s); for (int h = j + 1; h <= s.length(); h++) { string ss = s; ss.insert(ss.begin() + h, ')'); if (newcandi.find(ss) == newcandi.end()) newcandi.insert(ss); } } } } candi = newcandi; } public: vector<string> generateParenthesis(int n) { vector<string>re; if (n == 0) return re; set<string>candi; candi.insert("()"); while (n > 1) { do_once(candi); n--; } return vector<string>(candi.begin(), candi.end()); } };

accepted



0 0