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);
        }
    }
}

本文作者:bokerr

本文链接:https://www.cnblogs.com/bokers/p/15575200.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   bokerr  阅读(41)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起
  1. 1 404 not found REOL
404 not found - REOL
00:00 / 00:00
An audio error has occurred.