美文网首页
leetcode22 括号匹配

leetcode22 括号匹配

作者: 数据挖掘小菜 | 来源:发表于2017-11-21 23:02 被阅读0次

    leetcode刷题笔记

    leetcode22

    问题描述:Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.For example, given n = 3, a solution set is:[ "((()))","(()())", "(())()", "()(())", "()()()"]

    问题分析

    该问题是要求输出括号串的数目,本身括号是一种对称结构,所以可以采取回溯的方式来解决,依次输出左右括号,从而保证括号的对称,这里利用了深度优先遍历的思想。具体代码如下:

    public static List<String> generateParenthesis(int n) {
                    List<String> result = new ArrayList<>();
                    String sub = "";
                    generateParenthesisOneByOne(sub,result,n,n);
                    return result;
                }
    
    public static void generateParenthesisOneByOne(String sublist,List<String> list,int left,int right){
            if (left > right)
                return;
            if (left>0){
                generateParenthesisOneByOne(sublist+"(",list,left-1,right);
            }
            if (right>0){
                generateParenthesisOneByOne(sublist+")",list,left,right-1);
            }
            if (left == 0 && right == 0)
            {
                list.add(sublist);
                return;
            }
        }
    
      public static void main(String[] args){
          Scanner scanner = new Scanner(System.in);
          int n = scanner.nextInt();
          List<String> re = generateParenthesis(n);
          for (int i=0;i<re.size();i++){
              System.out.println(re.get(i));
          }
      }
    

    相关文章

      网友评论

          本文标题:leetcode22 括号匹配

          本文链接:https://www.haomeiwen.com/subject/kmpgvxtx.html