Leetcode22.括号生成

题目描述

数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。

示例:

输入:n = 3
输出:[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]

题解

DFS(java)

比较经典的dfs解法,比起全部遍历添加了两个剪枝条件。

class Solution {
    List<String> ans = new LinkedList<>();
    public void dfs(int left, int right, String s , int n) {
        if (s.length() == n * 2) {
            ans.add(s);
        }
        if (left < n) {
            dfs(left + 1, right, s + "(", n);
        }
        if (right < left) {
            dfs(left, right + 1, s + ")", n);
        }
    }
    public List<String> generateParenthesis(int n) {
        dfs(0, 0, "", n);
        return ans;
    }

复杂度分析

  • 时间复杂度: O ( 4 n n ) O(\frac{4^n}{\sqrt{n}}) O(n 4n) , 该复杂度为第n个卡特兰数
  • 空间复杂度: O ( n ) O(n) O(n) ,取决于递归栈的深度,最深为2n层

DFS2(java)

DFS搜索所有可能的组合情况,在添加在最后的输出列表之前对其有效性做检查。

trick: 在递归时可以使用char数组,方便遍历检查有效性;在最后输出时用new String(current) 直接构造新字符串。

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> combinations = new ArrayList();
        generateAll(new char[2 * n], 0, combinations);
        return combinations;
    }

    public void generateAll(char[] current, int pos, List<String> result) {
        if (pos == current.length) {
            if (valid(current))
                result.add(new String(current));
        } else {
            current[pos] = '(';
            generateAll(current, pos+1, result);
            current[pos] = ')';
            generateAll(current, pos+1, result);
        }
    }

    public boolean valid(char[] current) {
        int balance = 0;
        for (char c: current) {
            if (c == '(') balance++;
            else balance--;
            if (balance < 0) return false;
        }
        return (balance == 0);
    }
}
  • 时间复杂度: O ( 2 2 n n ) O(2^{2n}n) O(22nn)
  • 空间复杂度: O ( n ) O(n) O(n)
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值