力扣HOT100 - 22. 括号生成

解题思路:

class Solution {
    List<String> res = new ArrayList<>();

    public List<String> generateParenthesis(int n) {
        if (n <= 0) return res;
        getParenthesis("", n, n);
        return res;
    }

    private void getParenthesis(String str, int left, int right) {
        if (left == 0 && right == 0) {
            res.add(str);
            return;
        }
        if (left == right) {
            // 剩余左右括号数相等,下一个只能用左括号
            getParenthesis(str + "(", left - 1, right);
        } else if (left < right) {
            // 剩余左括号小于右括号,下一个可以用左括号也可以用右括号
            if (left > 0) getParenthesis(str + "(", left - 1, right);
            if (right > 0) getParenthesis(str + ")", left, right - 1);
        }
    }
}

相关推荐

  1. 22. 括号生成

    2024-04-30 06:42:05       10 阅读
  2. 刷题之22.括号生成

    2024-04-30 06:42:05       18 阅读
  3. 10020.有效的括号 || 栈

    2024-04-30 06:42:05       42 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-30 06:42:05       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-30 06:42:05       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-30 06:42:05       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-30 06:42:05       20 阅读

热门阅读

  1. arco.design重写message实现只提示一次错误的功能

    2024-04-30 06:42:05       10 阅读
  2. SQL LPAD函数使用

    2024-04-30 06:42:05       13 阅读
  3. RTCRTC

    2024-04-30 06:42:05       8 阅读
  4. golang垃圾回收

    2024-04-30 06:42:05       11 阅读
  5. Linux 系统中如何将网卡设置为桥接模式

    2024-04-30 06:42:05       10 阅读