Dynamic Programing: Damascus University
Dynamic Programing: Damascus University
Dynamic Programing
Damascus University
2 - Fibonacci Sequence
Recursive Solution:
int Fib(int n)
{
if (n<=1)
return 1;
else
return Fib(n-1)+Fib(n-2);
}
Complexity:
3 - Fibonacci Sequence
Recursive tree:
2) Bottom-up:
Iterative.
Starts from the base case.
If state X depends on state Y, then state Y must be calculated
before state X.
Implementing DP Solutions:
10
2) Bottom-up:
int BottomUp(state final_state)
{
DP[base_case_1]=base_case_answer_1;
DP[base_case_2]=base_case_answer_2;
...
for (state n) // for loop over all states from smaller to larger states.
{
int c1=DP[a]; // a,b,... are the states which state n depends on.
int c2=DP[b];
...
return DP[final_state];
}
Implementing DP Solutions:
11
2) Bottom-up:
Ex: Fibonacci Sequence:
int DP[100];
int BottomUpFib(int n)
{
DP[0]=1; // base cases
DP[1]=1;
for (int i=2;i<=n;i++) // for loop over all states from smaller to larger states.
{
int c1=DP[i-1]; // state (i) depends on (i-1) and (i-2)
int c2=DP[i-2];
return DP[n];
}
12 Classic DP Problems
Coin Change Problem:
Given a set of coins, for example {1,5,7}.
What is the minimum number of coins needed to achieve a value X ?
Ex: for X=10 the answer is 2 (5+5).
Steps
Steps for
for finding
finding a
a solution:
solution:
1)
1) The
Representing
The state
state is
is (number
(number
the given
of
of problem
processed
processed ascharacters
characters
states, wherefrom
fromthe
a,
a, answer
number
numberof of
ofeach
processed
state
processed
depends
characters
characters
on one from
from
or more
b),
b), (i,j)
(i,j)
smaller
depends
dependsstates.
on
on (i-1,j)
(i-1,j) and
and (i,j-1)
(i,j-1) and
and (i-1,j-
(i-1,j-
1).
1).
2) Finding the base cases. i.e. the states that have obvious answers.
2)
2) The
Finding
The base
basethe
case
case
base
is
is (0,0),
cases.
(0,0), the
the
i.e.answer
answer
the states
is
is 0.
0.that have obvious answers.
3) Writing the DP formula.
3)
3) Writing the DP formula.
22
Classic DP Problems
LCS Problem:
Top-Down Implementation:
string a,b;
int DP[1000][1000];
int TopDownLCS(int i,int j)
{
if (DP[i][j]!=-1)
return DP[i][j];
else if (i==0 && j==0)
return 0;
else
{
DP[i][j]=0;
if (i>0 && j>0 && a[i-1]==b[j-1])
DP[i][j]=TopDownLCS(i-1,j-1)+1;
else
{
if (i>0)
DP[i][j]=max(DP[i][j],TopDownLCS(i-1,j));
if (j>0)
DP[i][j]=max(DP[i][j],TopDownLCS(i,j-1));
}
}
}
23
Classic DP Problems
LCS Problem:
Bottom-Up Implementation:
string a,b;
int DP[1000][1000];
int BottomUpLCS(int n,int m)
{
DP[0][0]=0;
for (int i=0;i<=n;i++)
{
for (int j=0;j<=m;j++)
{
if (i==0 && j==0)
continue;
if (i>0 && j>0 && a[i-1]==a[j-1])
DP[i][j]=DP[i-1][j-1]+1;
else
{
if (i>0)
DP[i][j]=max(DP[i][j],DP[i-1][j]);
if (j>0)
DP[i][j]=max(DP[i][j],DP[i][j-1]);
}
}
}
return DP[n][m];
}
Training Problems:
24
Training Problems:
25
Training Problems:
26
Training Problems:
27
Training Problems:
28
Training Problems:
29
Training Problems:
30
Training Problems:
31
Training Problems:
32