码迷,mamicode.com
首页 > 其他好文 > 详细

022. Generate Parentheses

时间:2016-09-09 12:03:48      阅读:95      评论:0      收藏:0      [点我收藏+]

标签:

 1 class Solution {
 2 public:
 3     vector<string> generateParenthesis(int n) {
 4         vector<string> result;
 5         string current;
 6         string choice = "()";
 7         int numLeftBracket = 0; // 计数,左括号和右括号的差值,只需字符串中左括号的数量始终不小于右括号的数量,同时限制长度
 8         dfs(result, choice, current, n, numLeftBracket);
 9         return result;
10     }
11 private:
12     void dfs(vector<string>& result, const string& choice, string& current, int n, int numLeftBracket)
13     {
14         if (numLeftBracket == 0 && current.size() == n * 2) {
15             result.push_back(current);
16             return;
17         }
18         else {
19             if (numLeftBracket < 0 || numLeftBracket > n || current.size() > n * 2) return; // 这里需要注意限制current的长度
20             else {
21                 for (int i = 0; i < choice.size(); ++i) {
22                     if (numLeftBracket > 0) {
23                         current.push_back(choice[i]);
24                         if (choice[i] == () dfs(result, choice, current, n, numLeftBracket + 1);
25                         else dfs(result, choice, current, n, numLeftBracket - 1);
26                     }
27                     else {
28                         if (choice[i] == )) continue;
29                         else {
30                             current.push_back(choice[i]);
31                             dfs(result, choice, current, n, numLeftBracket + 1);
32                         }
33                     }
34                     current.pop_back();
35                 }
36             }
37         }
38     }
39 };

 

022. Generate Parentheses

标签:

原文地址:http://www.cnblogs.com/shadowwalker9/p/5855828.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!