Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Reading:
Dynamic Programming I “Dynamic Programming”, 15 CLRS
I “Dynamic Programming”, 5.3 GT
Jonathan Backer
Greedy works if some optimal solution contains the greedy choice.
backer@cs.ubc.ca
I Dijkstra’s algorithm always adds the cheapest vertex to the
shortest path tree (greedy).
Department of Computer Science I Dijkstra’s algorithm may not work with negative edge weights.
University of British Columbia
Algorithm TryEmAll(C ,n) This is inefficient because it recomputes the same subproblems
int N[C .length] over and over again.
for i ← 0 to N.length−1 do
N[i] ← 0 TryEmAll([1,3,4],90)
90
if n = 0 then
return N
89 87 86
N[1] ← ∞
for i ← 0 to C .length−1 do
88 86 85 86 84 83 85 83 82
if n ≥ C [i] then
subprob ← TryEmAll(C ,n − C [i])
A better idea: replace each recursive call with a table look-up.
if subprob.sum()+1 < N.sum() then
N ← subprob I Construct a table to store the optimal solution for each n.
N[i] ← N[i] + 1 I Iteratively increase n and compute its entry.
return N