Finding all combinations of well-formed brackets

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

    Groovy version based on markt's elegant c# solution above. Dynamically checking open and close (information was repeated in output and args) as well as removing a couple of extraneous logic checks.

    3.times{ 
        println bracks(it + 1)
    }
    
    def bracks(pairs, output=""){
        def open = output.count('(')
        def close = output.count(')')
    
        if (close == pairs) {
            print "$output "
        }
        else {
            if (open < pairs) bracks(pairs, "$output(")
            if (close < open) bracks(pairs, "$output)")
        }
        ""
    }
    

提交回复
热议问题