标签:mil spl turn 方法 cti 递归 (()) example color
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
标签:mil spl turn 方法 cti 递归 (()) example color
原文地址:https://www.cnblogs.com/yalphait/p/10334237.html