FZU Problem 2030 括号问题

/*
  对于小数据用这dfs,大数据就用递推的思想。
*/
#include <iostream>
#include <stdio.h>
#include <string>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <queue>
#include <map>
#include <stack>
#include <vector>
using namespace std ;
const int maxn = 20;
char str[maxn];
int num[maxn];
bool judge(char *st){
    int top = 0;
    int l = strlen(st);
    for(int i = 0;i < l;i++){
        if(st[i] == '(')
            top++;
        else
            if(top)
                top--;
            else
                return 0;
    }
    if(top)
        return 0;
    return 1;
}
int len,ans;
void dfs(int x){
    if(x == len){
        if(judge(str))
            ans++;
    }
    else{
        str[num[x]] = '(';
        dfs(x+1);
        str[num[x]] = ')';
        dfs(x+1);
    }
}
int main(){
    //freopen("test.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    while(~scanf("%s",str)){
        len = 0;
        int l = strlen(str);
        for(int i = 0;i < l;i++){
            if(str[i] == '?')
                num[len++] = i;
        }
        ans = 0;
        dfs(0);
        printf("%d\n",ans);
    }
    return 0;
}
/*
  对于数据比较小的,直接用dfs即可,数据要是比较大的话,dfs肯定TLE,所以这时应该采取递推的思想。
*/
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 1005;
char str[maxn];
int dp[maxn][maxn];
int main(){
    while(~scanf("%s",str)){
        int len = (int)strlen(str);
        dp[0][1] = 1;
        for(int i = 1;i < len;i++){
            for(int j = 0;j < len;j++){
                if(str[i] == '(')
                    dp[i][j] = dp[i-1][j-1];
                else if(str[i] == ')')
                    dp[i][j] = dp[i-1][j+1];
                else
                    dp[i][j] = dp[i-1][j-1] + dp[i-1][j+1];
            }
        }
        /*for(int i = 0;i < len;i++){
            for(int j =0;j < len;j++)
                printf("%d ",dp[i][j]);
            printf("\n");
        }*/
        printf("%d\n",dp[len - 1][0]);
    }
    return 0;
}
 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值