CC128 括号生成

描述

给出n对括号,请编写一个函数来生成所有的由n对括号组成的合法组合。

例如,给出n=3,解集为:

"((()))", "(()())", "(())()", "()()()", "()(())"

数据范围:1 \le n \le 81≤n≤8

示例1

输入:

1

复制返回值:

["()"]

复制

示例2

输入:

2

复制返回值:

["(())","()()"]
#include <stdio.h>

/*
Write a function Brackets(int n) that prints all combinations of well-
formed brackets. For Brackets(3) the output would be ((())) (()()) (())
() ()(()) ()()()

You can approach this the same way you'd do it by hand.  Build up the
string of brackets left to right.  For each position, you have a
decision of either ( or ) bracket except for two constraints:
(1) if you've already decided to use n left brackets, then you can't
use a another left bracket and
(2) if you've already used as many right as left brackets, then you
can't use another right one.

This suggests the following alorithm. Showing what happens on the
stack is a silly activity.
*/

// Buffer for strings of ().
char buf[1000];

// Continue the printing of bracket strings.
//   need is the number of ('s still needed in our string.
//   open is tne number of ('s already used _without_ a matching ).
//   tail is the buffer location to place the next ) or (.
void cont(int need, int open, int tail)
{
    // If nothing needed or open, we're done.  Print.
    if (need == 0 && open == 0) {
        printf("%s\n", buf);
        return;
    }

    // If still a need for (, add a ( and continue.
    if (need > 0) {
        buf[tail] = '(';
        cont(need - 1, open + 1, tail + 1);
    }

    // If still an open (, add a ) and continue.
    if (open > 0) {
        buf[tail] = ')';
        cont(need, open - 1, tail + 1);
    }
}

void Brackets(int n)
{
    cont(n, 0, 0);
}

int main(void)
{
    Brackets(4);
    return 0;
}

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值