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

[LeetCode] Generate Parentheses

时间:2015-06-13 15:27:17      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:

Well, there are two ways to add a open or close parenthesis to the current string.

  1. If number of ( is less than n, you can add (;
  2. If number of ) is less than number of (, you can add ).

Maintain a res for all the possible parenthesis and a temporary string sol for the current answer. Now we have the following code.

 1 class Solution {
 2 public:
 3     vector<string> generateParenthesis(int n) {
 4         vector<string> res;
 5         string sol;
 6         genParen(sol, 0, 0, n, res);
 7         return res;
 8     }
 9 private:
10     void genParen(string& sol, int open, int close, int total, vector<string>& res) {
11         if (open == total && close == total) {
12             res.push_back(sol);
13             return;
14         }
15         if (open < total) {
16             sol += (;
17             genParen(sol, open + 1, close, total, res);
18             sol.resize(sol.length() - 1);
19         }
20         if (close < open) {
21             sol += );
22             genParen(sol, open, close + 1, total, res);
23             sol.resize(sol.length() - 1);
24         }
25     }
26 }; 

 

[LeetCode] Generate Parentheses

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4573496.html

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