Finding all combinations of well-formed brackets

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

    Common Lisp:

    This doesn't print them, but does produce a list of lists of all the possible structures. My method is a bit different from the others'. It restructures the solutions to brackets(n - 1) such that they become brackets(n). My solution isn't tail recursive, but it could be made so with a little work.

    Code

    (defun brackets (n)
      (if (= 1 n)
          '((()))
          (loop for el in (brackets (1- n))
                when (cdr el)
                collect (cons (list (car el)) (cdr el))
                collect (list el)
                collect (cons '() el))))
    

提交回复
热议问题