动态规划&备忘录方法&递归方法

动态规划的基本思想是,将原问题拆分为若干子问题,自底向上的求解。其总是充分利用重叠子问题,即通过每个子问题只解一次,把解保存在一个表中,巧妙的避免了子问题的重复求解。

递归方法,采用的是自顶向下的思想,拆分为若干子问题,但是造成了子问题的重复求解。

备忘录方法,采用的也是自顶向下的思想,但是该方法维护了一个记录子问题解的表,虽然填表动作的控制结构更像递归方法,但是的确避免了子问题的重复求解。

下面以字符串的相似度来展示一下各方法的特点:

动态规划

递归:略

备忘录:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

const int N = 100;

int dist[N][N];

int minValue(int va, int vb, int vc)
{
	int temp = va;

	if(vb < temp)
		temp = vb;
	if(vc < temp)
		temp = vc;

	return temp;
}

int distance(string strA, int pABegin, int pAEnd, string strB, int pBBegin, int pBEnd)
{
	if(dist[pABegin][pBBegin]>=0)
		return dist[pABegin][pBBegin];

	if (pABegin > pAEnd)
	{
		if(pBBegin > pBEnd)
			dist[pABegin][pBBegin] = 0;
		else
			dist[pABegin][pBBegin] = pBEnd - pBBegin + 1;

		return dist[pABegin][pBBegin];
	}

	if (pBBegin > pBEnd)
	{
		if(pABegin > pAEnd)
			dist[pABegin][pBBegin] = 0;
		else
			dist[pABegin][pBBegin] = pAEnd - pBBegin + 1;

		return dist[pABegin][pBBegin];
	}

	if (strA[pABegin]==strB[pBBegin])
	{
		dist[pABegin][pBBegin] = distance(strA, pABegin+1, pAEnd, strB, pBBegin+1, pBEnd);

		return dist[pABegin][pBBegin];
	}
	else
	{
		int t1 = distance(strA, pABegin, pAEnd, strB, pBBegin+1, pBEnd);
		int t2 = distance(strA, pABegin+1, pAEnd, strB, pBBegin, pBEnd);
		int t3 = distance(strA, pABegin+1, pAEnd, strB, pBBegin+1, pBEnd);

		dist[pABegin][pBBegin] = minValue(t1, t2, t3)+1;

		return dist[pABegin][pBBegin];
	}
	
}

int main()
{
	string A;
	string B;

	cin>>A;
	cin>>B;

	for (int i=0; i<N; i++)
		for(int j=0; j<N; j++)
			dist[i][j] = -1;

	cout<<distance(A, 0, A.length()-1, B, 0, B.length()-1);
	return 0;
}


另一个例子请看考: 斐波那契数列


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值