Lecture4 RecursiveAlgo Vs DP
Lecture4 RecursiveAlgo Vs DP
Lecture4 RecursiveAlgo Vs DP
Lhouari Nourine
Master ICS
Recurrence equation:
T (1) = 1
T (n) = 2T ( n2 ) + n, n ≥ 2
Algorithm 4: Fib(n)
begin
if n ≤ 1 then
return(n);
else
return(Fib(n − 1) + Fib(n − 2));
Recurrence equation:
T (0) = T (1) = 1
T (n) = T (n − 1) + T (n − 2), n ≥ 2
Example: T (n) = 2T ( n3 ) + T ( n2 ) + n2
Idea:
1 Reuse already computed functions.
2 Cut the unnecessary subtrees.
The space complexity depends on the depth of the recursion tree; think of
the stack overflow!!!
For which problems the memoisation technique can improve the time
complexity?
Recurrence equation:
Base cases : S1 = 1 and Sk = 0 for all negative integers.
Sn = Sn−1 + Sn−3 + Sn−5
Knapsack Problem: A set of items S = {1, ..., n}, where item i has weight
wi and Find a subset S 0 ⊆ S such
P utility vi , and a knapsack capacity B. P
that i∈S 0 wi ≤ B and maximizes the utility i∈S 0 .
Let S(i, b) be the value of the optimal solution to the knapsack instance
defined by on i items and a capacity b.
Recurrence equation:
Base cases :
S(0, b) = 0 for 0 ≤ b ≤ B, no item
S(i, b) = −∞ for b < 0, illegal
S(i, b) = max(vi + S(i − 1, b − wi ), S(i − 1, b)) take i or not
where 1 ≤ i ≤ n, 0 ≤ b ≤ w .
Define subproblems:
D(S, v ): the length of the optimal path that visits every node in the
set S exactly once and ends at v .
There are approximately n2n subproblems
Answer is minv ∈V D(V , v ), where V is the given set of nodes
Recurrence equation
Consider a path that visits all nodes in S exactly once and ends at v .
Right before arriving v , the path comes from some u in S − {v }.
And that subpath has to be the optimal one that covers S − {v },
ending at u.
We just try all possible candidates for u
Problem
Questions to Answer (QA)
Instance : A set of questions {1, 2, 3, ..., n}, a set {p1 , p2 , p3 , ..., pn }
where pi corresponds to pints to receive for answering the question i,
and a set {f1 , f2 , f3 , ..., fn } where fi corresponds to the number of
questions following i that your are unable to solve when you solve the
question i.
Question : Compute a subset Q ⊆ {1, 2, 3, ..., n} that maximizes
P
i∈Q pi , and for each i ∈ Q, Q∩]i, i + fi ] = ∅.