题目: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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
题意解析:
给定n对括号,编写一个函数来生成所有格式良好的括号组合。
解题思路一:
利用递归,要想知道当前的所有组合,必须要知道上一个的所有组合,然后将()插入到每个组合的字符串的不同位置,去掉重复的即可。
public List<String> generateParenthesis(int n){
if (n == 1){
List<String> list1 = new ArrayList<>();
list1.add("()");
return list1;
}
Set<String> strings = new HashSet<>();
List<String> list2 = generateParenthesis(n-1);
for (String str : list2){
for (int i=0; i<str.length(); i++){
StringBuilder sb = new StringBuilder(str);
sb.insert(i,"()");
strings.add(sb.toString());
}
}
return new ArrayList<>(strings);
}
提交代码之后:
Runtime: 4 ms, faster than 10.73% of Java online submissions for Generate Parentheses.
Memory Usage: 37.4 MB, less than 96.24% of Java online submissions for Generate Parentheses.
可以看见,时间消耗得比较高,原因是每次都进行大量的组合运算。
解题思路二:
直接生成括号组合。定义一个字符串存储当前得到的字符串组合,然后递归left和right的值,每次使他们的值减一,同时加上对应的括号,(左边加(,右边加)),当left和right都等于0时,代表已经得到了一个符合条件的字符串,此时将此字符串加入到list中即可。
public List<String> generateParenthesis(int n) {
List<String> list = new ArrayList<String>();
generateOneByOne("", list, n, n);
return list;
}
public void generateOneByOne(String sublist, List<String> list, int left, int right){
if(left > right){
return;
}
if(left > 0){
generateOneByOne( sublist + "(" , list, left-1, right);
}
if(right > 0){
generateOneByOne( sublist + ")" , list, left, right-1);
}
if(left == 0 && right == 0){
list.add(sublist);
}
}
提交代码之后:
Runtime: 1 ms, faster than 96.31% of Java online submissions for Generate Parentheses.
Memory Usage: 37.8 MB, less than 71.43% of Java online submissions for Generate Parentheses.