首页 > 其他 > 详细

Generate Parentheses

时间:2016-08-10 00:50:21      阅读:229      评论: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:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

 

Analyse: As long as number of "(" is smaller than n, we can push "(", as long as number of ")" is smaller than "(", we can push ")". 

Runtime: 0ms.

 1 class Solution {
 2 public:
 3     vector<string> generateParenthesis(int n) {
 4         vector<string> result;
 5         if(!n) return result;
 6         
 7         helper(n, 0, 0, result, "");
 8         return result;
 9     }
10     
11     void helper(int n, int left, int right, vector<string>& result, string temp) {
12         if(left == n && right == n) {
13             result.push_back(temp);
14             return;
15         }
16         if(left < n) helper(n, left + 1, right, result, temp + "(");
17         if(right < left && right < n) helper(n, left, right + 1, result, temp + ")");
18     }
19 };

 

Generate Parentheses

原文:http://www.cnblogs.com/amazingzoe/p/5755006.html

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