码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode][JavaScript]Generate Parentheses

时间:2015-05-26 01:36:50      阅读:674      评论:0      收藏:0      [点我收藏+]

标签:

Generate Parentheses 

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:

"((()))", "(()())", "(())()", "()(())", "()()()"

https://leetcode.com/problems/generate-parentheses/

 

 


 

 

只有两个节点的bfs

 1 /**
 2  * @param {number} n
 3  * @return {string[]}
 4  */
 5 var generateParenthesis = function(n) { 
 6     var res = [];
 7     bfs("", 0, 0);
 8     return res;
 9 
10     function bfs(tmpStr, countL, countR){
11         if(countL === n && countR === n){
12             res.push(tmpStr);
13             return;
14         }
15         if(countL !== n ){
16             bfs(tmpStr + "(", countL + 1, countR);
17         }
18         if(countL > countR){
19             bfs(tmpStr + ")", countL, countR + 1);
20         }
21     }
22 };

 

 

[LeetCode][JavaScript]Generate Parentheses

标签:

原文地址:http://www.cnblogs.com/Liok3187/p/4529490.html

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