寻找合法字符串

给出一个正整数n,请给出所有的包含n个'('和n个')'的字符串,使得'('和')'可以完全匹配。

例如:

'(())()','()()()' 都是合法的;

'())()('是不合法的。

请按照__字典序__给出所有合法的字符串。

输入描述:

输入为1个正整数

输出描述:

输出为所有合法的字符串,用英文逗号隔开

示例1

输入

2

输出

(()),()()
#include<stdio.h>
#include<iostream>
using namespace std;
#define MAX 50
bool start = true;
void helpcore(char *array,int pos,int NumPre,int NumPost){
    if(NumPre>NumPost)
        return ;
    if(NumPre==0){
        while(NumPost){
            array[pos++]=')';
            NumPost--;
        }
        array[pos] = '\0';
        if(start){
            printf("%s",array);
            start=false;
        }
        else
            printf(",%s",array);
    }
    else{
        if(NumPre==NumPost){
            array[pos]='(';
            helpcore(array,pos+1,NumPre-1,NumPost);
        }
        else{
            array[pos]='(';
            helpcore(array,pos+1,NumPre-1,NumPost);
            array[pos]=')';
            helpcore(array,pos+1,NumPre,NumPost-1);
        }
    }

}
int main()
{
    char array[MAX]={0};
    int n;
    cin>>n;
    helpcore(array,0,n,n);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/strawqqhat/article/details/87907715