Finding all combinations of well-formed brackets

后端 未结 29 1642
盖世英雄少女心
盖世英雄少女心 2020-11-28 02:34

This came up while talking to a friend and I thought I\'d ask here since it\'s an interesting problem and would like to see other people\'s solutions.

The task is to

29条回答
  •  青春惊慌失措
    2020-11-28 03:03

    def @memo brackets ( n )
        => [] if n == 0 else around( n ) ++ pre( n ) ++ post( n ) ++ [ "()" * n) ]
    
    def @memo pre ( n )
        => map ( ( s ) => "()" ++ s, pre ( n - 1 ) ++ around ( n - 1 ) ) if n > 2 else []
    
    def @memo post ( n )
        => map ( ( s ) => s ++ "()", post ( n - 1 ) ++ around ( n - 1 ) ) if n > 2 else []
    
    def @memo around ( n )
        => map ( ( s ) => "(" ++ s ++ ")", brackets( n - 1 ) )
    

    (kin, which is something like an actor model based linear python with traits. I haven't got round to implementing @memo but the above works without that optimisation)

提交回复
热议问题