【leetcode-12】22. 括号生成

题目描述

给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。

例如,给出 n = 3,生成结果为:

[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/generate-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路

  1. 我自己的循环,是用()从头插入到尾,遍历,字符串拼接都很费时间
  2. 别人的递归,不断在尾部添加(,如果(数量大于)的数量或大于给定的n,return;
  3. 之后再在尾部添加)。

代码

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); 
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值