Finding all combinations of well-formed brackets

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

    public static void printAllValidBracePermutations(int size) {
        printAllValidBracePermutations_internal("", 0, 2 * size);
    }
    
    private static void printAllValidBracePermutations_internal(String str, int bal, int len) {
        if (len == 0) System.out.println(str);
        else if (len > 0) {
            if (bal <= len / 2) printAllValidBracePermutations_internal(str + "{", bal + 1, len - 1);
            if (bal > 0) printAllValidBracePermutations_internal(str + "}", bal - 1, len - 1);
        }
    }
    

提交回复
热议问题