小括号合法数目

#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]; //当不需要每种结果时,可不要数组x
				sum += element[i];
				--map[i];
			produceParenthesesBacktrack(t+1);
				sum -= element[i];
				++map[i];
			}
		}
	}
}

int main()
{

	produceParenthesesBacktrack(0);
  	cout << "总的结果数为:" << count << endl;
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值