找到了良好的括号内所有组合 [英] Finding all combinations of well-formed brackets

查看:171
本文介绍了找到了良好的括号内所有组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这来了,而跟一个朋友,我想我会问在这里,因为这是一个有趣的问题,并希望看到其他人的解决方案。

的任务是写一个函数括号(INT N),打印的合式括号从1所有的组合... N。对于支架(3)的输出将

 ()
(())()()
((()))(()())(())()()(())()()()
 

解决方案

拍了裂缝呢.. C#也。

 公共无效支架(INT N)
    {
        的for(int i = 1; I< = N;我++)
        {
            括号(,0,0,i)的;
        }
    }
    私人无效支架(字符串输出,诠释开,INT接近,诠释对)
    {
        如果((开放==对)及及(接近==对))
        {
            Console.WriteLine(输出);
        }
        其他
        {
            如果(开<对)
                支架(输出+(开+ 1,关闭对);
            如果(接近<开放)
                支架(输出+),打开,关闭+ 1对);
        }
    }
 

递归走的事实,你永远无法比对的所需数量的增加更多的开放支架的优势,你就别想比打开支架。

添加更多的右括号

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 write a function Brackets(int n) that prints all combinations of well-formed brackets from 1...n. For Brackets(3) the output would be

()
(())  ()()   
((()))  (()())  (())()  ()(())  ()()()

解决方案

Took a crack at it.. C# also.

    public void Brackets(int n)
    {
        for (int i = 1; i <= n; i++)
        {
            Brackets("", 0, 0, i);
        }
    }
    private void Brackets(string output, int open, int close, int pairs)
    {
        if((open==pairs)&&(close==pairs))
        {
            Console.WriteLine(output);
        }
        else
        {
            if(open<pairs)
                Brackets(output + "(", open+1, close, pairs);
            if(close<open)
                Brackets(output + ")", open, close+1, pairs);
        }
    }

The recursion is taking advantage of the fact that you can never add more opening brackets than the desired number of pairs, and you can never add more closing brackets than opening brackets..

这篇关于找到了良好的括号内所有组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆