美文网首页
括号生成

括号生成

作者: Haward_ | 来源:发表于2019-10-17 10:57 被阅读0次

描述:
给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。

例如,给出 n = 3,生成结果为:

[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]

思想:dfs+剪枝


class Solution {
  public List<String> generateParenthesis(int n) {
    String str = "()";
    List<String> res = new ArrayList<>();
    if(n==0) {
      return res;
    }
    LinkedList<Character> temp = new LinkedList<>();
    int left = 0;
    int right = 0;
    dfs(str,res,temp,n,left,right);
    return res;
  }

  private void dfs(String str, List<String> res, LinkedList<Character> temp, int n, int left, int right) {
    if(temp.size()==2*n) {
      if(isFit(temp)) {
        add2Temp(res,temp);
      }
      return;
    }
    if(left>n || right>n) {
      return;
    }

    for(int i=0;i<str.length();i++) {
      temp.add(str.charAt(i));
      if(i==0) {
        dfs(str,res,temp,n,left+1,right);
      }else {
        dfs(str,res,temp,n,left,right+1);
      }
      temp.pollLast();
    }
  }

  private boolean isFit(LinkedList<Character> temp) {
    LinkedList<Character> stack = new LinkedList<>();
    for(int i=0;i<temp.size();i++) {
      char c = temp.get(i);
      if(stack.size()==0) {
        stack.add(c);
      }else {
        if(c==')' && stack.getLast()=='(') {
          stack.pollLast();
        }else {
          stack.add(c);
        }
      }
    }
    return stack.size()==0;
  }

  private void add2Temp(List<String> res, LinkedList<Character> temp) {
    StringBuffer s = new StringBuffer();
    for(int i=0;i<temp.size();i++) {
      s.append(temp.get(i));
    }
    res.add(s.toString());
  }
}

相关文章

  • LeetCode-22. 括号生成

    参考:第7课-泛型递归、树的递归 LeetCode-22. 括号生成 22. 括号生成 数字 n 代表生成括号的对...

  • HJ77 火车进站

     火车进站问题等同于括号生成[1]。 BM60 括号生成。 给出n对括号,请编写一个函数来生成所有的由n对括号组成...

  • 括号生成 (有效括号)

    题目 数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。 示例: 输入...

  • 括号生成

    给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。 例如,给出 n = 3...

  • 括号生成

    描述:给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。 例如,给出 n ...

  • 括号生成

    题目来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/gene...

  • 括号生成

    题目 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。 例如,给出 n ...

  • 括号生成

    题目需求 /*** 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。* ...

  • 生成括号

    版权声明:本文为博主原创文章,转载请注明出处。个人博客地址:https://yangyuanlin.club欢迎来...

  • 括号生成

    题目描述:  给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。 解题思路...

网友评论

      本文标题:括号生成

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