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:
"((()))", "(()())", "(())()", "()(())", "()()()"
题目大意:
给定一个数字n,代表括号的对数,求n对括号匹配的所有情况。
思路:
拿到题的第一反应想到的是这道题是典型的递归,但是好长时间过去了依然不知道怎么递归。参考学长博客:http://blog.csdn.net/wwh578867817/article/details/46392701,得到规律左半括号永远大于等于右半括号。
代码1:
class Solution { public: std::vector<std::string> generateParenthesis(int n) { std::vector<std::string> result; if (n <= 0) { return result; } std::string s; addBrackets(n, n, s, result); return result; } private: void addBrackets(int left, int right, std::string s, std::vector<std::string> &result) { if (left == 0 && right == 0) { result.push_back(s); return; } if (left == right) { addBrackets(left - 1, right, s + "(", result); } else { if (left > 0) { addBrackets(left - 1, right, s + "(", result); } if (right > 0) { addBrackets(left, right - 1, s + ")", result); } } } };
代码2:
class Solution { public: //思想也是保证左半括号个数大于等于右半括号个数 std::vector<std::string> generateParenthesis(int n) { std::string s; std::vector<std::string> result; generate(n, n, s, result); return result; } void generate(int left, int right, std::string s, std::vector<std::string> &result){ if(left){ generate(left - 1, right, s + "(", result); //如果左半括号还没有用完直接加左半括号 if(left != right){ //如果左右不相等 generate(left, right - 1, s + ")", result); //加右半括号 } }else{ if(right){ //如果还剩右括号没有加入则将剩余的所有右括号都加入 result.push_back(s + std::string(right,')')); } } return; } };