您的位置:首页 > 编程语言 > Java开发

Leetcode刷题记——22. Generate Parentheses(生成括号)

2016-11-17 16:31 369 查看
一、题目叙述:

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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]


Subscribe to see which companies asked this question

二、解题思路:

这道题共用了两种解法,我自己的想法非常笨而且慢,看了别人的代码,简洁清晰。。。

解法一(我的):

1、题目要求给出N对括号的所有合法组合,n对括号的不同组合都可以通过给n-1对括号的不同组合添加一对括号实现,这样并不需要检查生成的括号是否合法,因为每次添加是把左右括号作为整体添加的。关键问题是如何添加括号?

2、例如,n = 2 时,要给n =1时的所有括号组合中的每个组合 即“()”添加一个括号生成新组合,那么添加的位置在这里可以有3处,分别是左括号前,左括号后,右括号后。即得到“()()”,“(())”,“()()”如下组合。

3、会发现通过这种方法生成的组合确实是都是合法的,但是会有重复,所以我就用最笨的方法,每次生成一个组合,与List里的字符串比较,没有出现过的组合再加进去(这里注意,不能用==比较字符串是否相等,因为==比较的是是否为一个对象,这里用equals)。

解法二(来自别人):

1、基本思路是,写括号,在每个位置,左括号剩余数若比右括号多,那么就是不合法的组合跳出;若左右括号剩余数都为0 ,那么填进List;

三、源码:

解法一:

import java.util.ArrayList;
import java.util.List;

public class Solution
{
public List<String> generateParenthesis(int n)
{
ArrayList<String> que = new ArrayList<String>();
if (n == 0)
return que;
que.add("");
for (int i = 0; i < n; i++)
{
int len = que.size();
for (int j = 0; j < len; j++)
{
String temp = que.remove(0);
for (int k = 0; k <= temp.length(); k ++)
{
StringBuilder build = new StringBuilder(temp);
build.insert(k, "()");
if (isTure(build.toString(), que))
que.add(build.toString());

aa85

}
}
}
return que;

}
public boolean isTure(String s, List<String> list)
{
for (int i = 0; i < list.size(); i++)
{
if (s.equals(list.get(i))) return false;
}
return true;
}
public static void main(String args[])
{
int a = 4;
Solution so = new Solution();
System.out.println(so.generateParenthesis(a));

}
}解法二:

import java.util.ArrayList;
import java.util.List;

public class Solution
{
public List<String> generateParenthesis(int n)
{
ArrayList<String> lst = new ArrayList<String>();
String s = "";
anew(lst,s,n,n);
return lst;
}
public void anew(ArrayList<String> lst, String s, int left, int right)
{
if (left == 0 && right == 0)
{
lst.add(s);
return;
}
if (left > right)
return;
if (left > 0)
{
anew(lst, s + "(", left - 1, right);
}
if (right > 0)
{
anew(lst, s + ")", left, right - 1);
}
}
public static void main(String[] args)
{
Solution sol = new Solution();
System.out.println(sol.generateParenthesis(4));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode java