【10】Regular Expression Matching
【17】Letter Combinations of a Phone Number
【22】Generate Parentheses (2019年2月13日)
给了一个N,生成N对括号的所有情况的字符串。
n = 3
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
题解:dfs生成。
1 class Solution { 2 public: 3 vector<string> generateParenthesis(int n) { 4 vector<string> res; 5 string str; 6 int left = n, right = n; 7 dfs(str, res, left, right); 8 return res; 9 } 10 void dfs(string& str, vector<string>& res, int left, int right) { 11 if (left == 0 && right == 0) { 12 res.push_back(str); 13 return; 14 } 15 if (left <= right && left - 1 >= 0) { 16 str += "("; 17 dfs(str, res, left-1, right); 18 str.pop_back(); 19 } 20 if (left < right && right - 1 >= 0) { 21 str += ")"; 22 dfs(str, res, left, right - 1); 23 str.pop_back(); 24 } 25 } 26 };