首页 > 其他 > 详细

[LeetCode]Generate Parentheses

时间:2016-03-09 00:04:24      阅读:193      评论:0      收藏:0      [点我收藏+]

题目描述:

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, 可以继续放左括号,当右括号数<左括号数时,可以继续放右括号。 

 1 class Solution {
 2 public:
 3     vector<string> generateParenthesis(int n) {
 4         vector<string> result;
 5         if (n > 0) {
 6             generateParenthesis(n, "", 0, 0, result);
 7         }
 8         
 9         return result;
10     }
11 private:
12     void generateParenthesis(int n, string s, int l, int r, vector<string> &result) {
13         if (l == n) {
14             result.push_back(s.append(n - r, )));
15             return;
16         }
17         generateParenthesis(n, s + (, l + 1, r, result);
18         
19         if (r < l) {
20            generateParenthesis(n, s + ), l, r + 1, result); 
21         }
22     }
23 };

 

[LeetCode]Generate Parentheses

原文:http://www.cnblogs.com/skycore/p/5256156.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!