Parentheses Sequence微软编程笔试

本文探讨了一种括号匹配问题,旨在通过最少的括号插入使原始括号序列变得匹配,并计算不同匹配方式的数量。文章提供了详细的动态规划解题思路及样例分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

描述

You are given a sequence S of parentheses. You are asked to insert into S as few parentheses as possible so that the resulting sequence T is well matched.

It's not difficult. But can you tell how many different T you can get?

Assume S = ()), you can get either (()) or ()().

输入

One line contains the sequence S.  

For 30% of the data, 1 ≤ |S| ≤ 10  

For 60% of the data, 1 ≤ |S| ≤ 200  

For 100% of the data, 1 ≤ |S| ≤ 1000  

输出

Output 2 integers indicating the minimum number of parentheses need to be inserted into S and the number of different T. The number of different T may be very large, so output the answer modulo 109+7.

样例输入
())
样例输出
1 2

只考虑左边(比右边)多的情况,也就是消掉匹配的()之后的比如(((((()消掉匹配的后只有(((((的情况
现在考虑如下"("比")"多
((()()( => (((

那么第一个(和第二个(之间最多只能有1个),至少0个
那么第二个(和第三个(之间最多只能有2个),至少0个
那么第三个(和第四个(之间最多只能有3个),至少1个
那么第四个(和第五个(之间最多只能有3个),至少1个
dp[i][j]:到第i+1个"("为止,有j个")"的方案数
k表示当前第i个"("和第i+1个"("之间有k个")"
dp[i][j] = sum(dp[i-1][j-k])
那么))))())))())))*(((((()(((()((,*号左边全是消不掉的),右边全是消不掉(,右边也就是上面讨论的情况,左边翻转一下也就是上面讨论情况,ans = ansl*ansr%MOD;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值