Finding all combinations of well-formed brackets

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

    F#:

    Here is a solution that, unlike my previous solution, I believe may be correct. Also, it is more efficient.

    #light
    
    let brackets2 n =
        let result = new System.Collections.Generic.List<_>()
        let a = Array.create (n*2) '_'
        let rec helper l r diff i =
            if l=0 && r=0 then
                result.Add(new string(a))
            else
                if l > 0 then
                    a.[i] <- '('
                    helper (l-1) r (diff+1) (i+1)
                if diff > 0 then
                    a.[i] <- ')'
                    helper l (r-1) (diff-1) (i+1)
        helper n n 0 0
        result
    

    Example:

    (brackets2 4) |> Seq.iter (printfn "%s")
    
    (*
    (((())))
    ((()()))
    ((())())
    ((()))()
    (()(()))
    (()()())
    (()())()
    (())(())
    (())()()
    ()((()))
    ()(()())
    ()(())()
    ()()(())
    ()()()()
    *)
    

提交回复
热议问题