自学内容网 自学内容网

括号生成-力扣热题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不要组合使用,容易造成时间复杂度过大!

原文地址:https://blog.csdn.net/Winnie12138_/article/details/140401275

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!