您的位置:首页 > 其它

LeetCode-22. Generate Parentheses

2017-02-15 19:42 330 查看
一、问题描述

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:

[

  "((()))",

  "(()())",

  "(())()",

  "()(())",

  "()()()"

]

二、解题思路



结构类似于二叉树,树叶即为我们所获得的一个结果,利用递归调用实现该二叉树。但需要注意两点,1左括号的最大个数为n;2.如果右括号的个数小于左括号的个数,则添加右括号,当且仅当左右括号数都为n时将该结果添加到列表中。

三、代码

public class Solution {
public List<String> generateParenthesis(int n) {
LinkedList<String> result=new LinkedList<String>();
if(n<=0)
return result;
GP(n,n,result,"");
return result;
/* result.add("()");
for(int i=1;i<n;i++){
while(result.peek().length()==i*2){
String temp1=result.remove();
result.add("("+temp1+")");
String temp2="()"+temp1;
String temp3=temp1+"()";
result.add(temp2);
if(!temp2.equals(temp3)){
result.add(temp3);
}
}
}
return result;
*/
}
public void GP(int left,int right,List<String> result,String temp){
if(left==0 && right==0){
result.add(temp);
return;
}

if(left>0)
GP(left-1,right,result,temp+"(");
if(right>left)
GP(left,right-1,result,temp+")");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: