题目描述
给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/generate-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路
- 我自己的循环,是用()从头插入到尾,遍历,字符串拼接都很费时间
- 别人的递归,不断在尾部添加(,如果(数量大于)的数量或大于给定的n,return;
- 之后再在尾部添加)。
代码
class Solution {
// *****************我自己写的循环版本,时间空间超多,太挫了*********************
public List<String> generateParenthesis(int n) {
List<String> list = new LinkedList<>();
if(n < 1) return list;
if(n == 1) {
list.add("()");
return list;
}
list.add("()");
int k = 1;
while(k < n){
int len = list.size();
while(len > 0){
String item = list.remove(0);
int length = item.length();
for(int i =0; i < length; i++){
list.add(item.substring(0, i) + "()" + item.substring(i, length));
}
len--;
}
k++;
}
HashSet h = new HashSet(list);
list.clear();
list.addAll(h);
return list;
}
// *****************网上的递归版本,还能说什么呢,牛逼*********************
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<String>();
generate(res, "", 0, 0, n);
return res;
}
//count1统计“(”的个数,count2统计“)”的个数
public void generate(List<String> res , String ans, int count1, int count2, int n){
if(count1 > n || count2 > n) return;
if(count1 == n && count2 == n) res.add(ans);
if(count1 >= count2){
String ans1 = new String(ans);
generate(res, ans+"(", count1+1, count2, n);
generate(res, ans1+")", count1, count2+1, n);
}
}
}