Finding all combinations of well-formed brackets

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

    F#:

    UPDATE: this answer is wrong. My N=4 misses, for example "(())(())". (Do you see why?) I will post a correct (and more efficient) algorithm shortly.

    (Shame on all you up-voters, for not catching me! :) )


    Inefficient, but short and simple. (Note that it only prints the 'nth' line; call in a loop from 1..n to get the output asked for by the question.)

    #light
    let rec brackets n =
        if n = 1 then
            ["()"]
        else
            [for s in brackets (n-1) do
                yield "()" ^ s
                yield "(" ^ s ^ ")"
                yield s ^ "()"]
    

    Example:

    Set.of_list (brackets 4) |> Set.iter (printfn "%s")
    (*
    (((())))
    ((()()))
    ((())())
    ((()))()
    (()(()))
    (()()())
    (()())()
    (())()()
    ()((()))
    ()(()())
    ()(())()
    ()()(())
    ()()()()
    *)
    

提交回复
热议问题