Finding all combinations of well-formed brackets

后端 未结 29 1678
盖世英雄少女心
盖世英雄少女心 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:15

    Haskell:

    I tried to come up with an elegant list monad-y way to this:

    import Control.Applicative
    
    brackets :: Int -> [String]
    brackets n = f 0 0 where
        f pos depth =
            if pos < 2*n
                then open <|> close
                else stop where
                    -- Add an open bracket if we can
                    open =
                        if depth < 2*n - pos
                            then ('(' :) <$> f (pos+1) (depth+1)
                            else empty
    
                    -- Add a closing bracket if we can
                    close = 
                        if depth > 0
                            then (')' :) <$> f (pos+1) (depth-1)
                            else empty
    
                    -- Stop adding text.  We have 2*n characters now.
                    stop = pure ""
    
    main = readLn >>= putStr . unlines . brackets
    

提交回复
热议问题