22. 括号生成

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

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

[

  "((()))",

  "(()())",

  "(())()",

  "()(())",

  "()()()"

]

import itertools

import numpy as np

class Solution:

    def generateParenthesis(self, n):

        """

        :type n: int

        :rtype: List[str]

        """

        datas = []

        result_true = []

        i = n

        while i!=1:

            datas.append(2*(i-1))

            datas.append(2*(i-1)-1)

            i-=1

        result = list(itertools.combinations(datas, n-1))

        print(result)

        lenght = result.__len__()-1

        while lenght!=-1:

            datas_child = np.ones(2*(n),dtype=int)

            datas_child[2*(n)-1]=-1

            lenght_child = result[lenght].__len__()-1

            while lenght_child!=-1:

                child_index = result[lenght][lenght_child]

                datas_child[child_index] = -1

                lenght_child -= 1

            result_lenght = datas_child.__len__()

            i=0

            result_child = 0

            ok = True

            while i<result_lenght:

                result_child+=datas_child[i]

                if result_child<0:

                    result.pop(lenght)

                    ok = False

                    break

                i+=1

            if ok:

                c = datas_child.astype('str')

                c[datas_child == 1] = '('

                c[datas_child == -1] = ')'

                result_true.append(''.join(c))

            lenght-=1

        return result_true


©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • "use strict";function _classCallCheck(e,t){if(!(e instanc...
    久些阅读 2,125评论 0 2
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 34,071评论 18 399
  • 空气污染加剧 可吸入粉尘增加 严峻的生存问题已经对我们构成挑战 威胁。 ...
    娜儿科阅读 262评论 0 0
  • 5月12日,十七岁如约而至。 黑色的十七岁,黑色的珠穆朗玛峰,即使早已攀过乔戈里峰三年,却依旧对珠峰心...
    秋羲和阅读 1,230评论 0 0
  • 我已经忘了喜欢一个人的感觉,可能我没有真正喜欢过一个人吧。中学暗恋的情愫已远去,那个他已经很早就不是我那时幻想和倾...
    黄土高坡上的风姑娘阅读 567评论 0 1

友情链接更多精彩内容