zoukankan      html  css  js  c++  java
  • Leetcode 22.生成括号对数

    生成括号对数

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

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

    [

    "((()))",

    "(()())",

    "(())()",

    "()(())",

    "()()()"

    ]

     1 class Solution {
     2     public List<String> generateParenthesis(int n) {
     3         List<String> combinations = new ArrayList();
     4         generateAll(new char[2 * n], 0, combinations);
     5         return combinations;
     6     }
     7 
     8     public void generateAll(char[] current, int pos, List<String> result) {
     9         if (pos == current.length) {
    10             if (valid(current))
    11                 result.add(new String(current));
    12         } else {
    13             current[pos] = '(';
    14             generateAll(current, pos+1, result);
    15             current[pos] = ')';
    16             generateAll(current, pos+1, result);
    17         }
    18     }
    19 
    20     public boolean valid(char[] current) {
    21         int balance = 0;
    22         for (char c: current) {
    23             if (c == '(') balance++;
    24             else balance--;
    25             if (balance < 0) return false;
    26         }
    27         return (balance == 0);
    28     }
    29 }

     1 class Solution {
     2     public List<String> generateParenthesis(int n) {
     3         List<String> ans = new ArrayList();
     4         backtrack(ans, "", 0, 0, n);
     5         return ans;
     6     }
     7 
     8     public void backtrack(List<String> ans, String cur, int open, int close, int max){
     9         if (cur.length() == max * 2) {
    10             ans.add(cur);
    11             return;
    12         }
    13 
    14         if (open < max)
    15             backtrack(ans, cur+"(", open+1, close, max);
    16         if (close < open)
    17             backtrack(ans, cur+")", open, close+1, max);
    18     }
    19 }

  • 相关阅读:
    简单的文件上传html+ashx
    URL重写
    图解classloader加载class的流程及自定义ClassLoader
    Linux下PS命令详解
    JAVA字符串格式化-String.format()的使用
    JAVA String.format 方法使用介绍
    MVC设计模式(Python)
    Jupyter NoteBook 的快捷键使用指南
    Hive常用函数
    Hive Tutorial(一)
  • 原文地址:https://www.cnblogs.com/kexinxin/p/10162977.html
Copyright © 2011-2022 走看看