Leetcode: NO.22 括号生成

回眸只為那壹抹淺笑 提交于 2020-04-10 10:15:42

题目

题目链接:https://leetcode-cn.com/problems/generate-parentheses

数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。

示例:

输入:n = 3
输出:[
       "((()))",
       "(()())",
       "(())()",
       "()(())",
       "()()()"
     ]

解题记录

看一下规律,起始一定是'(',左括号和右括号的个数一定相等且等于n,这里使用递归求出可行字符串插入到列表中:

class Solution {
    int N;
    List<String> total = new ArrayList<>();
    public List<String> generateParenthesis(int n) {
        N=n;
        addStr("(", 1, 0);
        return total;
    }
    
    public void addStr (String seq, int left, int right){
        if (seq.length() == N*2){
            total.add(seq);
        }else{
            if(left<N) addStr(seq+"(", left+1, right);
            if(right<N && right < left) addStr(seq+")", left, right+1);
        }
    }
}

在这里插入图片描述

优化

String类型换成char[]

class Solution {
    int N;
    List<String> result = new ArrayList<>();
    public List<String> generateParenthesis(int n) {
        N = n<<1;
        char[] seq = new char[N];
        addStr(seq, 0, N);
        return result;
    }

    public void addStr(char[] seq, int count, int rest){
        if (rest==0&&count==0){
            result.add(new String(seq));
        } else if (count>0&&rest>0){
            seq[N-rest] = '(';
            addStr(seq, count+1, rest-1);
            seq[N-rest] = ')';
            addStr(seq, count-1, rest-1);
        } else if(rest>0){
            seq[N-rest] = '(';
            addStr(seq, count+1, rest-1);
        }
    }
}

在这里插入图片描述
速度略有提升

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!