zoukankan      html  css  js  c++  java
  • letcode括号生成

    递归大法,空间换时间

        就是记录左右括号数,一旦右括号数大于左括号数,退出。
        当左右括号数相等,且等于n则为合法解。
    

    • 使用char数组取代StringBuilder可以减少内存使用,这样每次进行回溯时不需要再去删除末尾一位。
    class Solution {
        /**
         * 括号生成
         * */
        public List<String> generateParenthesis(int n) {
            List<String> result = new ArrayList<>();
            char[] temp = new char[n * 2];
            /**
             * L-左括号数
             * R-右括号数
             * L + R = temp 下标
             * */
            temp[0] = '(';
            deepParenthesis(result, temp, n, 1, 0);
            return result;
        }
    
        private void deepParenthesis(List<String> result, char[] temp, int n, int L, int R){
            if (L==R && L ==n){
                /** 左右括号数相等,且等于给定括号数 */
                result.add(String.valueOf(temp));
                return;
            }
            /** 左括号数小等于n,且不小于右括号数 */
            if (L <= n && L >= R){
                /** 下一步左括号 */
                temp[L + R] = '(';
                deepParenthesis(result, temp,n, L + 1, R);
                /** 下一步右括号 */
                temp[L + R] = ')';
                deepParenthesis(result, temp,n, L, R + 1);
            }
        }
    }
    
  • 相关阅读:
    angular-指令
    microbit 范例课程
    microsoft 为microbit.org 设计的课程
    Microbit 翻译计划及IDE 中文化
    Microbit MicroPython 介绍
    micro:bit 软件生态系统介绍
    Microbit 硬件架构介绍
    TCP协议和UDP协议下的socket
    爬虫-链家二手房
    函数相关
  • 原文地址:https://www.cnblogs.com/bokers/p/15575200.html
Copyright © 2011-2022 走看看