【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 };
View Code

相关文章:

  • 2021-08-09
  • 2021-09-15
  • 2021-11-30
  • 2022-12-23
  • 2021-08-18
  • 2022-12-23
  • 2021-08-27
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-12-26
  • 2022-12-23
  • 2022-12-23
  • 2021-06-09
  • 2022-01-30
  • 2022-02-15
相关资源
相似解决方案