//记忆化搜索
int fib(int n)
{
static vector<int> m_memory = vector<int>(n + 1, -1);
if (n == 0 || n == 1)
{
return 1;
}
if (m_memory[n] == -1)
{
m_memory[n] = fib(n - 1) + fib(n - 2);
}
return m_memory[n];
}
//普通的递归-----原始的解法
int fib2(int n)
{
if (n == 0|n==1)
{
return 1;
}
return fib2(n - 1) + fib2(n - 2);
}
//动态规划
int fib3(int n)
{
std::vector<int> m_mem(n + 1, -1);
m_mem[0] = 1;
m_mem[1] = 1;
for (int i = 2; i <= n;i++)
{
m_mem[i] = m_mem[i - 1] + m_mem[i - 2];
}
return m_mem[n];
}
int main()
{
//1,1,2,3,5,8,13
clock_t t1 = clock();
int n = fib(40);
clock_t t2 = clock();
cout <<"fib need time :"<< t2-t1 <<"fib(40):"<<n<< endl;
clock_t t3 = clock();
int n1 = fib2(40);
clock_t t4 = clock();
cout << "fib2 need time :" << t4 - t3 << "fib2(40):" << n1 << endl;
clock_t t5 = clock();
int n2 = fib3(40);
clock_t t6 = clock();
cout << "fib3 need time :" << t6 - t5 << "fib3(40):" << n2 << endl;
system("pause");
return 0;
}
结果:
从结果中看出无论是记忆搜索还是动态规划都比原始的效率要高出许多。这种思想值得我们学习。
总结:
动态规划: