Finding all combinations of well-formed brackets

后端 未结 29 1514
盖世英雄少女心
盖世英雄少女心 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:05
    //C program to print all possible n pairs of balanced parentheses  
    
    
    #include<stdio.h>
    
    void fn(int p,int n,int o,int c);
    
    void main()
    {
        int n;
        printf("\nEnter n:");
        scanf("%d",&n);
        if(n>0)  
            fn(0,n,0,0);
    }
    
    void fn(int p,int n,into,int c)
    {  
        static char str[100];
        if(c==n)
        {
            printf("%s\n",str);
            return;
        }
        else
        {
            if(o>c)
            {
                str[p]='}';
                fn(p+1,n,o,c+1);
            }
            if(o<n)
            {
                str[p]='{';
                fn(p+1,n;o+1,c);
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-28 03:08

    F#:

    UPDATE: this answer is wrong. My N=4 misses, for example "(())(())". (Do you see why?) I will post a correct (and more efficient) algorithm shortly.

    (Shame on all you up-voters, for not catching me! :) )


    Inefficient, but short and simple. (Note that it only prints the 'nth' line; call in a loop from 1..n to get the output asked for by the question.)

    #light
    let rec brackets n =
        if n = 1 then
            ["()"]
        else
            [for s in brackets (n-1) do
                yield "()" ^ s
                yield "(" ^ s ^ ")"
                yield s ^ "()"]
    

    Example:

    Set.of_list (brackets 4) |> Set.iter (printfn "%s")
    (*
    (((())))
    ((()()))
    ((())())
    ((()))()
    (()(()))
    (()()())
    (()())()
    (())()()
    ()((()))
    ()(()())
    ()(())()
    ()()(())
    ()()()()
    *)
    
    0 讨论(0)
  • 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<String> brackets(int n) {
        if(n == 1){
            Set<String> s = new HashSet<String>();
            s.add("()");
            return s;
        }else{
            Set<String> s1 = new HashSet<String>();
            Set<String> s2 = brackets(n - 1);
            for(Iterator<String> it = s2.iterator(); it.hasNext();){
                String s = it.next();
                s1.add("()" + s);
                s1.add("(" + s + ")");
                s1.add(s + "()");
            }
            s2.clear();
            s2 = null;
            return s1;
        }
    }
    
    0 讨论(0)
  • 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)")
        }
        ""
    }
    
    0 讨论(0)
  • 2020-11-28 03:10

    In C#

        public static void CombiParentheses(int open, int close, StringBuilder str)
        {
            if (open == 0 && close == 0)
            {
                Console.WriteLine(str.ToString());
            }
            if (open > 0) //when you open a new parentheses, then you have to close one parentheses to balance it out.
            {                
                CombiParentheses(open - 1, close + 1, str.Append("{"));
            }
            if (close > 0)
            {                
                CombiParentheses(open , close - 1, str.Append("}"));
            }
        }
    
    0 讨论(0)
  • 2020-11-28 03:11

    Simple solution in C++:

    #include <iostream>
    #include <string>
    
    void brackets(string output, int open, int close, int pairs)
    {
        if(open == pairs && close == pairs)
                cout << output << endl;
        else
        {
                if(open<pairs)
                        brackets(output+"(",open+1,close,pairs);
                if(close<open)
                        brackets(output+")",open,close+1,pairs);
        }
    }
    
    int main()
    {
        for(int i=1;i<=3;i++)
        {
                cout << "Combination for i = " << i << endl;
                brackets("",0,0,i);
        }
    }
    

    Output:

    Combination for i = 1
    ()
    Combination for i = 2
    (())
    ()()
    Combination for i = 3
    ((()))
    (()())
    (())()
    ()(())
    ()()()
    
    0 讨论(0)
提交回复
热议问题