招银2018[编程题]寻找合法字符串

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

例如:

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

'())()('是不合法的。
#include <stdio.h>
#include <iostream>
using namespace std;

#define MAX   50  
bool start = true;

//pos:       此时的位置下标
//NumPre:    剩余的左括号数目
//NumPost:  剩余的右括号数目
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{ // NumPre <= NumPost
            array[pos] = '(';
            helpCore(array, pos + 1, NumPre - 1, NumPost);
            array[pos] = ')';
            helpCore(array, pos + 1, NumPre, NumPost - 1);
        }
    }

    return;

}

int main()
{
    char array[MAX] = {0};
    //memset(array, '0', sizeof(array));
    int n;
    cin >> n;
    helpCore(array, 0, n, n);

    return 0;
}

猜你喜欢

转载自www.cnblogs.com/wqpkita/p/9556692.html