Finding all combinations of well-formed brackets

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

    why cant this is as simple as this, this idea is quite simple

    brackets(n) --> '()' + brackets(n-1) 0 '(' + brackets(n-1) + ')' 0 brackets(n-1) + '()'

    where 0 is the concatenation operation above

    public static Set brackets(int n) {
        if(n == 1){
            Set s = new HashSet();
            s.add("()");
            return s;
        }else{
            Set s1 = new HashSet();
            Set s2 = brackets(n - 1);
            for(Iterator it = s2.iterator(); it.hasNext();){
                String s = it.next();
                s1.add("()" + s);
                s1.add("(" + s + ")");
                s1.add(s + "()");
            }
            s2.clear();
            s2 = null;
            return s1;
        }
    }
    

提交回复
热议问题