括号生成

描述:
给出 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());
  }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 题目 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。 例如,给出 n ...
    半亩房顶阅读 376评论 0 1
  • 题目描述: 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。 例如,给出...
    LeeYunFeng阅读 1,377评论 0 50
  • 题目 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。 例如,给出 n ...
    玖月晴阅读 1,060评论 0 1
  • 22. 括号生成 描述 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。...
    GoMomi阅读 359评论 0 0
  • 在口语中,“好色”应为贬义词,大家都觉得一个人一旦贴上了好色的标签,一定是生性风流,生活作风有问题,见到入眼的异性...
    做个不平凡的人阅读 1,974评论 0 1