19.1.29 [LeetCode 22] Generate Parentheses
Posted TobicYAL
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了19.1.29 [LeetCode 22] 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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
1 class Solution { 2 public: 3 vector<string>build(int toclose, int toopen) { 4 vector<string>ans; 5 if (toclose == 0 && toopen == 0) { 6 ans.push_back(""); 7 return ans; 8 } 9 if (toclose > 0) { 10 vector<string>closeone = build(toclose - 1, toopen); 11 for (int i = 0; i < closeone.size(); i++) 12 ans.push_back(")" + closeone[i]); 13 } 14 if (toopen > 0) { 15 vector<string>openone = build(toclose + 1, toopen - 1); 16 for (int i = 0; i < openone.size(); i++) 17 ans.push_back("(" + openone[i]); 18 } 19 return ans; 20 } 21 vector<string> generateParenthesis(int n) { 22 return build(0, n); 23 } 24 };
一开始使用了递归方法,很慢,然后我看到还有其他解法是这样的??
1 class Solution { 2 public: 3 vector<string> generateParenthesis(int n) { 4 vector<string>ans; 5 if (n == 0) { 6 ans.push_back(""); 7 return ans; 8 } 9 set<string>_ans; 10 vector<string>tmp = generateParenthesis(n - 1); 11 for (int i = 0; i < tmp.size(); i++) { 12 string now = tmp[i]; 13 _ans.insert("()" + now); 14 for (int j = 0; now[j]; j++) { 15 if (now[j] == ‘(‘) 16 _ans.insert(now.substr(0, j + 1) + "()" + now.substr(j + 1)); 17 } 18 } 19 return vector<string>(_ans.begin(), _ans.end()); 20 } 21 };
这种方法很奇妙,是基于n-1递推出n的
因为所有n解都可以删去一个完整的()获得一个n-1解,所以在这里只要在n-1解上可以加()的位置加上一个()并且排除重复解即可得到结果
以上是关于19.1.29 [LeetCode 22] Generate Parentheses的主要内容,如果未能解决你的问题,请参考以下文章
19.1.29 [LeetCode 23] Merge k Sorted Lists
19.1.29 [LeetCode 21] Merge Two Sorted Lists
gen_server:啥是`start_monitor/4`中的`Mon`?