Finding all combinations of well-formed brackets

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

    In javascript / nodejs.

    The program was originally meant to answer the Ultimate Question, but it is just perfect to enumerate the valid brackets combinations.

    function* life(universe){
        if( !universe ) yield '';
        for( let everything = 1 ; everything <= universe ; ++everything )
            for( let meaning of life(everything - 1) )
                for( let question of life(universe - everything) )    
                    yield question + '(' + meaning + ')';
    }
    let love = 5;
    let answer = [...life(love)].length;
    console.log(answer);
    
    function brackets(n){
        for( k = 1 ; k <= n ; k++ ){
            console.log(...life(k));
        }
    }
    
    brackets(5);
    

提交回复
热议问题