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
比如这组数据就不对