• leetcode 括号


    1. 括号(0809)

    设计一种算法,打印n对括号的所有合法的(例如,开闭一一对应)组合。

    说明:解集不能包含重复的子集。

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

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

    class Solution {
        List<String> list = new ArrayList<>();
        char[] arr = new char[]{'(',')'};
        public List<String> generateParenthesis(int n) {
            StringBuilder sb = new StringBuilder();
            backtrack(sb,n,0,0);
            return list;
        }
        //countl表示左括号的数量,countr表示右括号的数量
        public void backtrack(StringBuilder sb,int n,int countl,int countr){
            if(countl < countr || countl > n){
                return;
            }
            if(sb.length() == 2*n){
                list.add(sb.toString());
            }
            for(char c : arr){
                sb.append(c);
                if(c == '('){
                    countl++;
                    backtrack(sb,n,countl,countr);
                    sb.deleteCharAt(sb.length()-1);
                    countl--;
                }else{
                    countr++;
                    backtrack(sb,n,countl,countr);
                    sb.deleteCharAt(sb.length()-1);
                    countr--;
                }
                
            }
    
        }
    }
    

    2. 有效的括号(20)

    class Solution {
        public boolean isValid(String s) {
            int len = s.length();
            if(len % 2 == 1) return false;
            char[] arr = s.toCharArray();
            Stack<Character> sin = new Stack<>();
            Stack<Character> sou = new Stack<>();
            for(char c : arr){
                sin.push(c);
            }
            while(!sin.isEmpty()){
                char tmp = sin.pop();
                if(tmp == ']' || tmp == '}' ||tmp == ')') 
                    sou.push(tmp);
                else{
                    if(sou.isEmpty()) return false;
                    boolean b = isValidhelper(tmp,sou.pop());
                    if(!b) return false;
                }
            }
            return true;
        }
        public boolean isValidhelper(char c1,char c2){
            if(c1 == '(' && c2 == ')') return true;
            if(c1 == '[' && c2 == ']') return true;
            if(c1 == '{' && c2 == '}') return true;
            return false;
        }
    }
    

    3. 有效的括号(20)

  • 相关阅读:
    SpringBoot入门学习(二)
    SpringBoot入门学习(一)
    eclipse调试程序界面简单介绍使用
    利用URLConnection来发送POST和GET请求
    查看用户所属的组
    linux下创建用户,给用户设置密码,给用户授权
    新linux系统上rz 与sz命令不可用
    pom.xml文件报错:web.xml is missing and <failOnMissingWebXml> is set to true
    MySql采用GROUP_CONCAT合并多条数据显示的方法
    Mysql计算时间差
  • 原文地址:https://www.cnblogs.com/aslanvon/p/13262852.html
Copyright © 2020-2023  润新知