POJ 2192 (DP) 或者 搜索

http://www.ahathinking.com/archives/173.html

注意怎么想DP,先把问题用递归求解。

总之,要先想到怎么用递归来暴力求解,这样就先给出了一个答案,然后就会知道了那些东西被重复计算了

就可以定义出DP的状态方程了

比如这题,递归的话,肯定是要么从前向后匹配要么从后向前,一样的,这里代码从后向前了

匹配的时候就是a的前i个,和b的前j个能匹配c的前i+j+1个,就是一个个向后匹配的过程

那么决策就是第能和a[i]或者b[j]哪个匹配了

所以先用递归做,然后再想DP就好想多了

#include <stdio.h>
#include <algorithm>
#include <string>
#include <iostream>


using namespace std;

string a;
string b;
string c;
int dfs_search(int i, int j)
{
        if (i == -1 && j == -1)
                return 1;
        if (i>=0 && a[i] == c[i+j+1])
                //return dfs_search(i-1, j);
                if (dfs_search(i-1, j))
                        return 1;
        if (j>=0 && b[j] == c[i+j+1])
                //return dfs_search(i, j-1);
                if (dfs_search(i, j-1))
                        return 1;

        return 0;

}

int main()
{
        int n = 0;
        int i = 0;

        cin>>n;
        while (n--) {
                cin>>a;
                cin>>b;
                cin>>c;
                int ret = dfs_search(a.length()-1,b.length()-1);
                cout<<"Data set "<<++i<<": "<<(ret==1?"yes":"no")<<endl;
        }
        //cout<<a;
        //cout<<a<<" "<<b<<" "<<c<<" "<<endl;

}

这个递归,注意,注释掉的两个return是不对的。因为函数直接在第一个return返回了,走不到第二个的。注意递归的思考

cat treet cattreet

比如这组数据就不对

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值