小括号合法数目

来源:互联网 发布:windows原理 编辑:程序博客网 时间:2024/05/09 07:11
#include <IOSTREAM>using namespace std;#define N  12//问题描述: 给定6对(),问能有多少种合法的组合//基本思路: 设)代表-1,)代表1,则对于一种组合()()()()())(,不合法的情况就是,从右往左求和时,如果出现sum<0则肯定不对。在求到第是一个)时sum==-1<0,故不合法。//(((())))()(),sum依次为:1, 2, 3, 4, 3, 2, 1, 0, 1, 0, 1, 0.故合法 int element[2] = {-1, 1}; char ch[5] = ")i("; //-1+1 ==0, 1+1 == 2.所以0位和2位上为括号int map[2] = {6,6};int x[N];int sum = 0;int count = 0;void produceParenthesesBacktrack(int t){if (t>=N){++count;for (int i=0; i< N; i++){cout << ch[x[i]+1]; //当不需要每种结果时,可不要数组x}cout << endl;}else{for (int i=0; i<2; i++){if (map[i] > 0 && (sum+element[i])>=0){x[t] = element[i]; //当不需要每种结果时,可不要数组xsum += element[i];--map[i];produceParenthesesBacktrack(t+1);sum -= element[i];++map[i];}}}}int main(){produceParenthesesBacktrack(0);  cout << "总的结果数为:" << count << endl;return 0;}

0 0
原创粉丝点击