Finding all combinations of well-formed brackets

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

    A simple F#/OCaml solution :

    let total_bracket n =
        let rec aux acc = function
            | 0, 0 -> print_string (acc ^ "\n")
            | 0, n -> aux (acc ^ ")") (0, n-1)
            | n, 0 -> aux (acc ^ "(") (n-1, 1)
            | n, c ->
                    aux (acc ^ "(") (n-1, c+1);
                    aux (acc ^ ")") (n,   c-1)
        in
        aux "" (n, 0)
    

提交回复
热议问题