括号生成-力扣热题100-回溯法-java实现

括号生成

力扣链接

  • 由于我一直记得大一学习“数据结构课”的时候,在老师讲解“栈”的时候有“括号匹配”的经典例题,于是当我看到这道题的时候第一反应是用栈,其实大可不必;
  • 当然,我在用栈之后遇到了一些困难,最后也终于ac了,但是需要分享一些心得体会:
    • 用stack.size()来看左括号的数量不太靠谱,可能会出现入栈的左括号数目>n的情况,下面可以直接运行代码来看我打印的内容:
      在这里插入图片描述
      可以看出虽然我括号生成的结果是对的,但是其实很多时候栈并没有清空就达到了current长度==2*max的条件(说明生成的左右括号数目并不对等)!
      代码如下:
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;
class Solution {
    public List<String> generateParenthesis(int n) {
//回溯and栈 输入 数字
        //规则:(就入栈,String加上(,如果是)就出栈,string加上)
        List<String> result=new ArrayList<>();
        if (n==0) return result;
        Stack<Character> st=new Stack<>();
        StringBuffer sb=new StringBuffer();
        dfs(result, "", st,  n);
        return result;
    }
    private void dfs(List<String> result, String current, Stack<Character> stack, int max) {
        if (current.length() == max * 2) {
            System.out.println("栈"+stack);
            if (stack.isEmpty()) {
                result.add(current);
            }
            return;
        }
        if (stack.size() < max) {
            stack.push('(');

            dfs(result, current + "(", stack, max);
            stack.pop();
        }
        if (!stack.isEmpty() ) {
            stack.pop();
            dfs(result, current + ")", stack, max);
            stack.push('(');
        }
    }




}
class Main {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int n = 3;
        List<String> results = solution.generateParenthesis(n);
        System.out.println("Generated Parentheses Combinations:");
        for (String s : results) {
            System.out.println(s);
        }
    }
}
修改

直接用一个变量来记录左括号和右括号的数目最为保险

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<>();
        if (n == 0) return result;
        dfs(result, "", 0, 0, n);
        return result;
    }

    private void dfs(List<String> result, String current, int open, int close, int max) {
        if (current.length() == max * 2) {
            result.add(current);
            return;
        }
//如果左括号的数目还小于总数,则
        if (open < max) {
            dfs(result, current + "(", open + 1, close, max);
        }

        if (close < open) {
            dfs(result, current + ")", open, close + 1, max);
        }
    }
}


  • 注:尽量做题的时候递归和stack不要组合使用,容易造成时间复杂度过大!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Beiwen_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值