您的位置:首页 > 其它

LeetCode Generate Parentheses

2016-01-02 15:10 288 查看
题目:

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,表示的是括号的对数,然后将所有合理的括号对数的形式输出。

题解:

将这题抽象成一棵树来处理,也就是采用采用递归来做,具体过程见下图:



就是采用上述过程,其中左子树表示的是添加左括号,右子树表示的是添加右括号。其中添加左括号的标准是当这个left值大于0,而当左子树的值大于右子树的值时,则返回空,说明已经不可能了。

public List<String> generateParenthesis(int n)
{
if(n < 0)
return null;
List<String> list = new ArrayList<String>();
String str = new String();
dfs(list,str,n,n);
return list;
}
public void dfs(List<String> list,String str,int left,int right)
{
if(left > right)
return;
if(left == 0 && right == 0)
list.add(str);
if(left > 0)
dfs(list,str + "(",left - 1,right);
if(right > 0)
dfs(list,str + ")",left,right - 1);
}非常巧妙,可以好好理解一下。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: