您的位置:首页 > 其它

Generate Parentheses

2015-08-10 20:55 267 查看

1. Problem

给定n对括号,生成所有可能的括号组合

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:

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


2. Solution

采用树的方式来选择生成所有的组合结果树,每种组合是树的一个遍历分支。

有两种方法,基本一样的。

第一种,定义三个变量:

lLeft:表示还没有用的左括号数;

rLeft:表示还没有用的右括号数;

now:表示当前已用的字符串;

其中lLeft<=rLeft始终成立。则有如下判断:

lLeft == 0:左括号用完,加上剩下的右括号,构建一个完整的串;

lLeft != 0:

接下来可以加一个左括号(总是可以)

如果lLeft < rLeft,则接下来也可以加一个右括号

代码如下:

public class Solution {
List<String> res;
public void expand( String now, int i, int j, int n ){
//finish matching
if( i == n ){
res.add( now );
return;
}
//all left parentheses are used
if( i + j == n )
expand( now + ")", i+1, j-1, n );
//there're still unused left parentheses
else{
//there're still unmatched left parentheses
if( j > 0 ){
expand( now + "(", i, j+1, n );
expand( now + ")", i+1, j-1, n );
}
//all used left parentheses are matched at present
else if( j == 0 )
expand( now + "(", i, j+1, n );
}
}

public List<String> generateParenthesis( int n ){
res = new ArrayList<String>();
expand( "(", 0, 1, n );
return res;
}
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: