Finding all combinations of well-formed brackets

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

    results = []
    num = 0
    
    def print_paratheses(left, right):
        global num
        global results
    
        # When nothing left, print the results.
        if left == 0 and right == 0:
            print results
            return
    
        # pos is the next postion we should insert parenthesis.
        pos = num - left - right
        if left > 0:
            results[pos] = '('
            print_paratheses(left - 1, right)
    
        if left < right:
            results[pos] = ')'
            print_paratheses(left, right - 1)
    
    def print_all_permutations(n):
        global num
        global results
        num = n * 2
        results = [None] * num
        print_paratheses(n, n)
    

    Reference: Permutations of Parentheses

提交回复
热议问题