《王道》分治法、动态规划与贪心算法

《王道》分治法、动态规划与贪心算法

1 分治法


2 动态规划



    例1


int c[100][100];
int LCS_LENGTH(const char *X, char *Y)
{
	if (X == NULL && Y == NULL)
		return 0;
	int m = strlen(X);
	int n = strlen(Y);
	c[0][0] = 0;
	for (int i = 1; i < m; i++)
		c[i][0] = 0;
	for (int i = 1; i < n; i++)
		c[0][i] = 0;
	for (int i = 1; i <= m; i++)
	{
		for (int j = 1; j <= n; j++)
		{
			if (X[i] == Y[j])
				c[i][j] = c[i - 1][j - 1] + 1;
			else
				c[i][j] = max(c[i][j - 1], c[i - 1][j]);
		}
	}
	return c[m][n];
}


    例2 



    这样,可以写出如下递归程序:

#include <iostream>
#include <string.h>
using namespace std;

int minValue(int x, int y, int z)
{
	if (x<y)
	{
		if (y < z)
			return x;
		else
			return x < z ? x : z;
	}
	else
	{
		if (x < z)
			return y;
		else
			return y < z ? y : z;
	}
}

int calculateStringDistance(string strA, int pABegin, int pAEnd, string strB, int pBBegin, int pBEnd)
{
	if (pABegin > pAEnd)                //边界条件,strA处理完毕
	{
		if (pBBegin > pBEnd)
			return 0;
		else
			return pBEnd - pBBegin + 1;
	}
	if (pBBegin > pBEnd)                //边界条件,strB处理完毕
	{
		if (pABegin > pAEnd)
			return 0;
		else
			return pAEnd - pABegin + 1;
	}
	if (strA[pABegin] == strB[pBBegin])              //如果strA的首字母等于strB的首字母
		return calculateStringDistance(strA,  pABegin + 1, pAEnd, strB, pBBegin + 1, pBEnd);
	else
	{
		int t1 = calculateStringDistance(strA, pABegin + 1, pAEnd, strB, pBBegin, pBEnd);
		int t2 = calculateStringDistance(strA, pABegin , pAEnd, strB, pBBegin + 1, pBEnd);
		int t3 = calculateStringDistance(strA, pABegin + 1, pAEnd, strB, pBBegin + 1, pBEnd);
		return minValue(t1, t2, t3) + 1;
	}
}

3 贪心算法

练习


猜你喜欢

转载自blog.csdn.net/qq_27022241/article/details/80324471