递归+分治,求一个数列的最大值和最小值
#include <iostream>
#include <stdlib.h>
using namespace std;
int max2(int A[], int lo, int hi, int &x1, int &x2)
{
if (lo + 2 == hi)
{
if (A[lo]<A[hi - 1])
{
x1 = A[hi - 1];
x2 = A[lo];
}
else
{
x1 = A[lo];
x2 = A[hi - 1];
}
return 0;
}
if (lo + 3 == hi)
{
if (A[lo]>A[lo + 1])
{
if (A[lo + 1]>A[lo + 2])
{
x1 = A[lo];
x2 = A[lo + 1];
}
else
{
if (A[lo]>A[lo + 2])
{
x1 = A[lo];
x2 = A[lo + 2];
}
else
{
x1 = A[lo + 2];
x2 = A[lo];
}
}
}
else
{
if (A[lo]>A[lo + 2])
{
x1 = A[lo + 1];
x2 = A[lo];
}
else
{
if (A[lo + 1]>A[lo + 2])
{
x1 = A[lo + 1];
x2 = A[lo + 2];
}
else
{
x1 = A[lo + 2];
x2 = A[lo + 1];
}
}
}
return 0;
}
int mi = (lo + hi) / 2;
int x1l, x2l;
max2(A, lo, mi, x1l, x2l);
int x1r, x2r;
max2(A, mi, hi, x1r, x2r);
if (A[x1l]>A[x2r])
{
x1 = x1l; x2 = (A[x2l]>A[x1r]) ? x2l : x1r;
}
else
{
x1 = x1r; x2 = (A[x1l]>A[x2r]) ? x1l : x2r;
}
return 0;
}
int main()
{
int a[5] = { 910, 118, 44, 333,6116};
int x1l, x2l;
max2(a, 0, 5 ,x1l, x2l);
cout << x1l << " "<< x2l;
getchar();
return 0;
}
动态规划
斐波那契数列
int fib(n) {return (2<n)?n:fib(n-1)+fib(n-2);}
O(pow(黄金分割数,n))=O(pow(2,n))
迭代
1.记忆
2.动态规划,颠倒计算方向
f= 0;g=1;
while(0<n--)
{
g=g+f;
f=g-f;
}
return g;
最长公共子序列
子序列:由序列中若干字符,按原相对次序构成
求最长公共子序列的长度
LCS:递归
A[0,n]和B[0,m]
(0)n=-1或m=-1,则区作空序列(“”)
(1)A[n]='x'=B[m],则取作LCS(A[0,n),B[0,m))+'x' //decrease
(2)A[n]!=B[m]则在LCS(A[0,n],b[0,m))与LCS(A[0,n),b[0,m])取更长者