# Dynamic Programming | Set 1 (Overlapping Subproblems Property)

1 重叠子问题（Overlapping Subproblems）

2 最优子结构（Optimal Substructure）

# 1 重叠子问题

/* simple recursive program for Fibonacci numbers */
int fib(int n)
{
if ( n <= 1 )
return n;
return fib(n-1) + fib(n-2);
}

1 Memoization (Top Down)

2 Tabulation (Bottom Up)

# 1 记忆化（Memoization）——Top Down

/* Memoized version for nth Fibonacci number */
#include<stdio.h>
#define NIL -1
#define MAX 100

int lookup[MAX];

/* Function to initialize NIL values in lookup table */
void _initialize()
{
int i;
for (i = 0; i < MAX; i++)
lookup[i] = NIL;
}

/* function for nth Fibonacci number */
int fib(int n)
{
if(lookup[n] == NIL)
{
if ( n <= 1 )
lookup[n] = n;
else
lookup[n] = fib(n-1) + fib(n-2);
}

return lookup[n];
}

int main ()
{
int n = 40;
_initialize();
printf("Fibonacci number is %d ", fib(n));
getchar();
return 0;
}

# 2 制表（Tabulation）——Bottom Up

/* tabulated version */
#include<stdio.h>
int fib(int n)
{
int f[n+1];
int i;
f[0] = 0;   f[1] = 1;
for (i = 2; i <= n; i++)
f[i] = f[i-1] + f[i-2];

return f[n];
}

int main ()
{
int n = 9;
printf("Fibonacci number is %d ", fib(n));
getchar();
return 0;
}

posted @ 2015-06-18 20:36  Acjx  阅读(571)  评论(0编辑  收藏  举报