59、回溯-括号生成

思路:

括号是成对出现,首先左括号可以放n个,右括号也可以放n个。如果当前左括号放了3了,右括号放了4个,错了,如果左括号放了5个,右括号放了4个。可以,继续放右括号即可。所以可以设计:

1、当前左括号-右括号>0?大于可以放右括号

2、当前左括号还剩下多少个可以放 >0 可以继续放左括号

代码如下:

复制代码
 public List<String> generateParenthesis(int n) {
        List<String> ans=new ArrayList<>();
        if (n<1){
            return ans;
        }
        char[] path = new char[n * 2];
        process(0,0, n,path,ans);
        return ans;
    }

    /**
     * 
     * @param index 下标
     * @param leftNum 左括号-右括号还剩下几个
     * @param leftNumAll 左边一共可以放几个
     * @param path
     * @param ans
     */
    private void process(int index, int leftNum, int leftNumAll, char[] path, List<String> ans) {
        if (index==path.length){
            ans.add(String.valueOf(path));
        }else {
            if (leftNum>0){
                path[index]=')';
                process02(index+1,leftNum-1,leftNumAll,path,ans);
            }
            if (leftNumAll>0){
                path[index]='(';
                process02(index+1,leftNum+1,leftNumAll-1,path,ans);
            }
        }
    }
相关推荐
Liu62888几秒前
C++中的模板方法模式
开发语言·c++·算法
qq_334903157 分钟前
高性能网络协议栈
开发语言·c++·算法
光电笑映9 分钟前
STL 源码解剖系列:map/set 的底层复用与红黑树封装
c语言·数据结构·c++·算法
阿贵---11 分钟前
模板编译期循环展开
开发语言·c++·算法
2601_9540236611 分钟前
Beyond the Hype: Deconstructing the 2025 High-Performance Stack for Agencies
java·开发语言·算法·seo·wordpress·gpl
沉鱼.4411 分钟前
滑动窗口问题
数据结构·算法
深念Y11 分钟前
Windows 11 23H2 搜狗输入法卸载后任务栏严重卡顿问题分析
windows
sheeta199814 分钟前
LeetCode 每日一题笔记 日期:2025.03.23 题目:1594.矩阵的最大非负积
笔记·leetcode·矩阵
ysa05103017 分钟前
二分+前缀(预处理神力2)
数据结构·c++·笔记·算法
2401_8331977319 分钟前
嵌入式C++电源管理
开发语言·c++·算法