SlideShare une entreprise Scribd logo
1  sur  4
Télécharger pour lire hors ligne
Computer Science 385
                                     Analysis of Algorithms
                                     Siena College
                                     Spring 2011

                  Topic Notes: Dynamic Programming
We next consider dynamic programming, a technique for designing algorithms to solve problems
by setting up recurrences with overlapping subproblems (smaller instances), solving those smaller
instances, remembering their solutions in a table to avoid recomputation, then using the subprob-
lem solutions from the table to obtain a solution to the original problem.
The idea comes from mathematics, where “programming” means “planning”.


Simple Example: Fibonacci Numbers
You have certainly seen the Fibonacci sequence before, defined by:


                                  F (n) = F (n − 1) + F (n − 2)
                                  F (0) = 0
                                  F (1) = 1

A direct computation using this formula would involve recomputation of many Fibonacci numbers
before F (n).
But if instead, we store the answers to the subproblems in a table (in this case, just an array), we
can avoid that recomputation. For example, when we compute F (n), we first need F (n − 1), then
F (n − 2). But the computation of F (n − 1) will also have computed F (n − 2). With a dynamic
programming technique, that answer will have been stored, so F (n − 2) is immediately available
once we have computed it once.
With the Fibonacci sequence, we can take a complete “bottom up” approach, realizing that we will
need answers to all smaller subproblems (F (0) up to F (n − 1)) in the process of computing F (n),
we can populate an array with 0 in element 0, 1 in element 1, and all successive elements with the
sum of the previous two. This makes the problem solvable in linear time, but uses linear space.
Moreover, with this approach, we need only keep the most recent two numbers in the sequence,
not the entire array. So we can still get a linear time solution constant space.


Binomial Coefficients
Another example you’ve probably seen before is the computation of binomial coefficients: the
values C(n, k) in the binomial formula:


                (a + b)n = C(n, 0)an + · · · + C(n, k)an−k bk + · · · + C(0, n)bn .
CS 385                              Analysis of Algorithms                           Spring 2011



These numbers are also the nth row of Pascal’s triangle.
The recurrences that will allow us to compute C(n,k):


                   C(n, k) = C(n − 1, k − 1) + C(n − 1, k) for n > k > 0
                   C(n, 0) = 1
                   C(n, n) = 1

As with the Fibonacci recurrence, the subproblems are overlapping – the computation of C(n −
1, k − 1) and C(n − 1, k) will involve the computation of some of the same subproblems. So a
dynamic programming approach is appropriate.
The following algorithm will fill in the table of coefficients needed to compute C(n, k):

binomial(n,k)
  for i=0 to n
    for j=0 to min(i,k)
      if j==0 or j==i
        C[i][j] = 1
      else
        C[i][j] = C[i-1][j-1] = C[i-1][j]
  return C[i][k]

It’s been a while since we did a more formal analysis of an algorithm’s efficiency.
The basic operation will be the addition in the else. This occurs once per element that we
compute. In the first k + 1 rows, the inner loop executes i times. For the remaining rows, the
inner loop executes k + 1 times. There are no differences in best, average, and worst cases: we go
through the loops in their entirety regardless of the input.
So we can compute the number of additions A(n, k) as:


                                        k     i−1          n       k
                           A(n, k) =                1+                 1
                                        i=1 j=1          i=k+1 j=1
                                        k                      n
                                    =         (i − 1) +            k
                                        i=1               i=k+1
                                        (k − 1)k
                                    =            + k(n − k) ∈ Θ(nk).
                                           2



Knapsack Problem
                                                    2
CS 385                                  Analysis of Algorithms                               Spring 2011



We now revisit the knapsack problem, which we first considered with a brute-force approach.
Recall the problem:
Given n items with weights w1 , w2 , ..., wn and values v1 , v2 , ..., vn , what is the most vaulable subset
of items that can fit into a knapsack that can hold a total weight W .
When we first considered the problem, we generated all possible subsets and selected the one that
resulted in the largest total value where the sums of the weights were less than or equal to W .
To generate a more efficient approach, we use a dynamic programming approach. We can break
the problem down into overlapping subproblems as follows:
Consider the instance of the problem defined by first i items and a capacity j (j ≤ W ).
Let V [i, j] be optimal value of such an instance, which is the value of an optimal solution consid-
ering only the first i items that fit in a knapsack of capacity j.
We can then solve it by considering two cases: the subproblem that includes the ith item, and the
subproblem that does not.
If we are not going to include the ith item, the optimal subset’s value (considering only items 0
through i − 1) would be V [i − 1, j].
If we do include item i (which is only possible if j −wi ≥ 0), its value is obtained from the optimal
subset of the first i − 1 items that can fit within a capacity of j − wi , as vi + V [i − 1, j − wi ].
It’s also possible that the ith item does not fit (where j − w1 < 0), in which case the optimal subset
is V [i − 1, j].
We can formulate these into a recurrence:

                             max {V [i − 1, j], vi + V [i − 1, j − wi ]} if j − w1 ≥ 0
               V [i, j] =
                             V [i − 1, j]                                if j − wi < 0

Combine with some initial conditions:
V [0, j] = 0 for j ≥ 0, V [i, 0] = 0 for i ≥ 0.
The solution to our problem is the value V [n, W ].
The text has an example in Figure 8.13, where the solution is obtained in a “bottom up” fashion,
filling in the table row by row or column by column, until we get our ultimate answer at in the
lower right corner. This guarantees we will compute each subproblem exactly once and is clearly
Θ(nW ) in time and space.
One problem with that approach is the fact that we are computing some subproblems that will
never be used in a recurrence starting from V [n, W ].
An alternate approach, this time working from the top (the solution) down (the subproblems), is to
solve each subproblem as it’s needed. But...to avoid recomputing subproblems, we remember the
answers to subproblems we have computed and just use them when they exist.


                                                     3
CS 385                                Analysis of Algorithms                            Spring 2011



The approach uses a technique called memory functions. These work just like regular functions,
but do what we described above. At the start of the function, it looks to see if the requested instance
has already been solved. If so, we just return the previously-computed result. If not, we compute
it, save it in the table of answers in case it’s needed again, then return the answer.
The following pseudocode implements this memory function idea for the knapsack problem:

Globals:
W[1..n]: item weights
values[1..n]: item values
V[0..n][0..W]: subproblem answers, starting all 0’s in first row/col,
               -1’s elsewhere
mf_knapsack(i,j)
  if (V[i][j] < 0)
    if (j < W[i])
      V[i][j] = mf_knapsack(i-1, j)
    else
      V[i][j] = max(mf_knapsack(i-1, j),
                    values[i] + mf_knapsack(i-1, j-W[i]))
  return V[i][j]

Applying this approach to the text’s example results in only 11 of the 20 values that were not
initial conditions are computed, but only one value is reused. Larger instances would result in
more subproblems being unneeded and more being reused.




                                                  4

Contenu connexe

Tendances

Eigen values and eigen vectors engineering
Eigen values and eigen vectors engineeringEigen values and eigen vectors engineering
Eigen values and eigen vectors engineering
shubham211
 
Specific function examples
Specific function examplesSpecific function examples
Specific function examples
Leo Crisologo
 
Chapter 4 dis 2011
Chapter 4 dis 2011Chapter 4 dis 2011
Chapter 4 dis 2011
noraidawati
 
Mathematical induction
Mathematical inductionMathematical induction
Mathematical induction
Sman Abbasi
 
Weatherwax cormen solutions
Weatherwax cormen solutionsWeatherwax cormen solutions
Weatherwax cormen solutions
kirankoushik
 

Tendances (20)

Ma2002 1.19 rm
Ma2002 1.19 rmMa2002 1.19 rm
Ma2002 1.19 rm
 
5.1 greedy 03
5.1 greedy 035.1 greedy 03
5.1 greedy 03
 
Mgm
MgmMgm
Mgm
 
Eigen values and eigen vectors engineering
Eigen values and eigen vectors engineeringEigen values and eigen vectors engineering
Eigen values and eigen vectors engineering
 
Solve Equations
Solve EquationsSolve Equations
Solve Equations
 
Hypothesis of Riemann's (Comprehensive Analysis)
 Hypothesis of Riemann's (Comprehensive Analysis) Hypothesis of Riemann's (Comprehensive Analysis)
Hypothesis of Riemann's (Comprehensive Analysis)
 
Lecture 9 f17
Lecture 9 f17Lecture 9 f17
Lecture 9 f17
 
Andrei rusu-2013-amaa-workshop
Andrei rusu-2013-amaa-workshopAndrei rusu-2013-amaa-workshop
Andrei rusu-2013-amaa-workshop
 
Specific function examples
Specific function examplesSpecific function examples
Specific function examples
 
Chapter 4 dis 2011
Chapter 4 dis 2011Chapter 4 dis 2011
Chapter 4 dis 2011
 
METHOD OF JACOBI
METHOD OF JACOBIMETHOD OF JACOBI
METHOD OF JACOBI
 
Mathematical induction
Mathematical inductionMathematical induction
Mathematical induction
 
Semi-Supervised Regression using Cluster Ensemble
Semi-Supervised Regression using Cluster EnsembleSemi-Supervised Regression using Cluster Ensemble
Semi-Supervised Regression using Cluster Ensemble
 
How to find a cheap surrogate to approximate Bayesian Update Formula and to a...
How to find a cheap surrogate to approximate Bayesian Update Formula and to a...How to find a cheap surrogate to approximate Bayesian Update Formula and to a...
How to find a cheap surrogate to approximate Bayesian Update Formula and to a...
 
Weatherwax cormen solutions
Weatherwax cormen solutionsWeatherwax cormen solutions
Weatherwax cormen solutions
 
Non-sampling functional approximation of linear and non-linear Bayesian Update
Non-sampling functional approximation of linear and non-linear Bayesian UpdateNon-sampling functional approximation of linear and non-linear Bayesian Update
Non-sampling functional approximation of linear and non-linear Bayesian Update
 
The Probability that a Matrix of Integers Is Diagonalizable
The Probability that a Matrix of Integers Is DiagonalizableThe Probability that a Matrix of Integers Is Diagonalizable
The Probability that a Matrix of Integers Is Diagonalizable
 
Eighan values and diagonalization
Eighan values and diagonalization Eighan values and diagonalization
Eighan values and diagonalization
 
Lecture 12 f17
Lecture 12 f17Lecture 12 f17
Lecture 12 f17
 
balakrishnan2004
balakrishnan2004balakrishnan2004
balakrishnan2004
 

Similaire à Sienna 10 dynamic

Dynamic1
Dynamic1Dynamic1
Dynamic1
MyAlome
 
Sienna 4 divideandconquer
Sienna 4 divideandconquerSienna 4 divideandconquer
Sienna 4 divideandconquer
chidabdu
 
Daa:Dynamic Programing
Daa:Dynamic ProgramingDaa:Dynamic Programing
Daa:Dynamic Programing
rupali_2bonde
 
Calculus Application Problem #3 Name _________________________.docx
Calculus Application Problem #3 Name _________________________.docxCalculus Application Problem #3 Name _________________________.docx
Calculus Application Problem #3 Name _________________________.docx
humphrieskalyn
 

Similaire à Sienna 10 dynamic (20)

5.3 dynamic programming 03
5.3 dynamic programming 035.3 dynamic programming 03
5.3 dynamic programming 03
 
AOA ppt.ppt
AOA ppt.pptAOA ppt.ppt
AOA ppt.ppt
 
Chapter 16
Chapter 16Chapter 16
Chapter 16
 
Linear programing problem
Linear programing problemLinear programing problem
Linear programing problem
 
9 - DynamicProgramming-plus latihan.ppt
9 - DynamicProgramming-plus latihan.ppt9 - DynamicProgramming-plus latihan.ppt
9 - DynamicProgramming-plus latihan.ppt
 
Dynamic1
Dynamic1Dynamic1
Dynamic1
 
Dynamic Programming.pptx
Dynamic Programming.pptxDynamic Programming.pptx
Dynamic Programming.pptx
 
Dynamic programming - fundamentals review
Dynamic programming - fundamentals reviewDynamic programming - fundamentals review
Dynamic programming - fundamentals review
 
Pydata Katya Vasilaky
Pydata Katya VasilakyPydata Katya Vasilaky
Pydata Katya Vasilaky
 
Sienna 4 divideandconquer
Sienna 4 divideandconquerSienna 4 divideandconquer
Sienna 4 divideandconquer
 
Signals and Systems Homework Help.pptx
Signals and Systems Homework Help.pptxSignals and Systems Homework Help.pptx
Signals and Systems Homework Help.pptx
 
Daa:Dynamic Programing
Daa:Dynamic ProgramingDaa:Dynamic Programing
Daa:Dynamic Programing
 
Knapsack Dynamic
Knapsack DynamicKnapsack Dynamic
Knapsack Dynamic
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
02 Notes Divide and Conquer
02 Notes Divide and Conquer02 Notes Divide and Conquer
02 Notes Divide and Conquer
 
Calculus Application Problem #3 Name _________________________.docx
Calculus Application Problem #3 Name _________________________.docxCalculus Application Problem #3 Name _________________________.docx
Calculus Application Problem #3 Name _________________________.docx
 
test pre
test pretest pre
test pre
 
Vector spaces
Vector spacesVector spaces
Vector spaces
 
Maths Assignment Help
Maths Assignment HelpMaths Assignment Help
Maths Assignment Help
 
Dynamic programming1
Dynamic programming1Dynamic programming1
Dynamic programming1
 

Plus de chidabdu

Sienna 12 huffman
Sienna 12 huffmanSienna 12 huffman
Sienna 12 huffman
chidabdu
 
Sienna 11 graphs
Sienna 11 graphsSienna 11 graphs
Sienna 11 graphs
chidabdu
 
Sienna 9 hashing
Sienna 9 hashingSienna 9 hashing
Sienna 9 hashing
chidabdu
 
Sienna 8 countingsorts
Sienna 8 countingsortsSienna 8 countingsorts
Sienna 8 countingsorts
chidabdu
 
Sienna 7 heaps
Sienna 7 heapsSienna 7 heaps
Sienna 7 heaps
chidabdu
 
Sienna 6 bst
Sienna 6 bstSienna 6 bst
Sienna 6 bst
chidabdu
 
Sienna 5 decreaseandconquer
Sienna 5 decreaseandconquerSienna 5 decreaseandconquer
Sienna 5 decreaseandconquer
chidabdu
 
Sienna 3 bruteforce
Sienna 3 bruteforceSienna 3 bruteforce
Sienna 3 bruteforce
chidabdu
 
Sienna 2 analysis
Sienna 2 analysisSienna 2 analysis
Sienna 2 analysis
chidabdu
 
Sienna 1 intro
Sienna 1 introSienna 1 intro
Sienna 1 intro
chidabdu
 
Sienna 13 limitations
Sienna 13 limitationsSienna 13 limitations
Sienna 13 limitations
chidabdu
 
Unit 3 basic processing unit
Unit 3   basic processing unitUnit 3   basic processing unit
Unit 3 basic processing unit
chidabdu
 
Unit 5 I/O organization
Unit 5   I/O organizationUnit 5   I/O organization
Unit 5 I/O organization
chidabdu
 
Algorithm chapter 1
Algorithm chapter 1Algorithm chapter 1
Algorithm chapter 1
chidabdu
 
Algorithm chapter 11
Algorithm chapter 11Algorithm chapter 11
Algorithm chapter 11
chidabdu
 
Algorithm chapter 10
Algorithm chapter 10Algorithm chapter 10
Algorithm chapter 10
chidabdu
 
Algorithm chapter 9
Algorithm chapter 9Algorithm chapter 9
Algorithm chapter 9
chidabdu
 
Algorithm chapter 8
Algorithm chapter 8Algorithm chapter 8
Algorithm chapter 8
chidabdu
 
Algorithm chapter 7
Algorithm chapter 7Algorithm chapter 7
Algorithm chapter 7
chidabdu
 
Algorithm chapter 6
Algorithm chapter 6Algorithm chapter 6
Algorithm chapter 6
chidabdu
 

Plus de chidabdu (20)

Sienna 12 huffman
Sienna 12 huffmanSienna 12 huffman
Sienna 12 huffman
 
Sienna 11 graphs
Sienna 11 graphsSienna 11 graphs
Sienna 11 graphs
 
Sienna 9 hashing
Sienna 9 hashingSienna 9 hashing
Sienna 9 hashing
 
Sienna 8 countingsorts
Sienna 8 countingsortsSienna 8 countingsorts
Sienna 8 countingsorts
 
Sienna 7 heaps
Sienna 7 heapsSienna 7 heaps
Sienna 7 heaps
 
Sienna 6 bst
Sienna 6 bstSienna 6 bst
Sienna 6 bst
 
Sienna 5 decreaseandconquer
Sienna 5 decreaseandconquerSienna 5 decreaseandconquer
Sienna 5 decreaseandconquer
 
Sienna 3 bruteforce
Sienna 3 bruteforceSienna 3 bruteforce
Sienna 3 bruteforce
 
Sienna 2 analysis
Sienna 2 analysisSienna 2 analysis
Sienna 2 analysis
 
Sienna 1 intro
Sienna 1 introSienna 1 intro
Sienna 1 intro
 
Sienna 13 limitations
Sienna 13 limitationsSienna 13 limitations
Sienna 13 limitations
 
Unit 3 basic processing unit
Unit 3   basic processing unitUnit 3   basic processing unit
Unit 3 basic processing unit
 
Unit 5 I/O organization
Unit 5   I/O organizationUnit 5   I/O organization
Unit 5 I/O organization
 
Algorithm chapter 1
Algorithm chapter 1Algorithm chapter 1
Algorithm chapter 1
 
Algorithm chapter 11
Algorithm chapter 11Algorithm chapter 11
Algorithm chapter 11
 
Algorithm chapter 10
Algorithm chapter 10Algorithm chapter 10
Algorithm chapter 10
 
Algorithm chapter 9
Algorithm chapter 9Algorithm chapter 9
Algorithm chapter 9
 
Algorithm chapter 8
Algorithm chapter 8Algorithm chapter 8
Algorithm chapter 8
 
Algorithm chapter 7
Algorithm chapter 7Algorithm chapter 7
Algorithm chapter 7
 
Algorithm chapter 6
Algorithm chapter 6Algorithm chapter 6
Algorithm chapter 6
 

Dernier

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Dernier (20)

Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 

Sienna 10 dynamic

  • 1. Computer Science 385 Analysis of Algorithms Siena College Spring 2011 Topic Notes: Dynamic Programming We next consider dynamic programming, a technique for designing algorithms to solve problems by setting up recurrences with overlapping subproblems (smaller instances), solving those smaller instances, remembering their solutions in a table to avoid recomputation, then using the subprob- lem solutions from the table to obtain a solution to the original problem. The idea comes from mathematics, where “programming” means “planning”. Simple Example: Fibonacci Numbers You have certainly seen the Fibonacci sequence before, defined by: F (n) = F (n − 1) + F (n − 2) F (0) = 0 F (1) = 1 A direct computation using this formula would involve recomputation of many Fibonacci numbers before F (n). But if instead, we store the answers to the subproblems in a table (in this case, just an array), we can avoid that recomputation. For example, when we compute F (n), we first need F (n − 1), then F (n − 2). But the computation of F (n − 1) will also have computed F (n − 2). With a dynamic programming technique, that answer will have been stored, so F (n − 2) is immediately available once we have computed it once. With the Fibonacci sequence, we can take a complete “bottom up” approach, realizing that we will need answers to all smaller subproblems (F (0) up to F (n − 1)) in the process of computing F (n), we can populate an array with 0 in element 0, 1 in element 1, and all successive elements with the sum of the previous two. This makes the problem solvable in linear time, but uses linear space. Moreover, with this approach, we need only keep the most recent two numbers in the sequence, not the entire array. So we can still get a linear time solution constant space. Binomial Coefficients Another example you’ve probably seen before is the computation of binomial coefficients: the values C(n, k) in the binomial formula: (a + b)n = C(n, 0)an + · · · + C(n, k)an−k bk + · · · + C(0, n)bn .
  • 2. CS 385 Analysis of Algorithms Spring 2011 These numbers are also the nth row of Pascal’s triangle. The recurrences that will allow us to compute C(n,k): C(n, k) = C(n − 1, k − 1) + C(n − 1, k) for n > k > 0 C(n, 0) = 1 C(n, n) = 1 As with the Fibonacci recurrence, the subproblems are overlapping – the computation of C(n − 1, k − 1) and C(n − 1, k) will involve the computation of some of the same subproblems. So a dynamic programming approach is appropriate. The following algorithm will fill in the table of coefficients needed to compute C(n, k): binomial(n,k) for i=0 to n for j=0 to min(i,k) if j==0 or j==i C[i][j] = 1 else C[i][j] = C[i-1][j-1] = C[i-1][j] return C[i][k] It’s been a while since we did a more formal analysis of an algorithm’s efficiency. The basic operation will be the addition in the else. This occurs once per element that we compute. In the first k + 1 rows, the inner loop executes i times. For the remaining rows, the inner loop executes k + 1 times. There are no differences in best, average, and worst cases: we go through the loops in their entirety regardless of the input. So we can compute the number of additions A(n, k) as: k i−1 n k A(n, k) = 1+ 1 i=1 j=1 i=k+1 j=1 k n = (i − 1) + k i=1 i=k+1 (k − 1)k = + k(n − k) ∈ Θ(nk). 2 Knapsack Problem 2
  • 3. CS 385 Analysis of Algorithms Spring 2011 We now revisit the knapsack problem, which we first considered with a brute-force approach. Recall the problem: Given n items with weights w1 , w2 , ..., wn and values v1 , v2 , ..., vn , what is the most vaulable subset of items that can fit into a knapsack that can hold a total weight W . When we first considered the problem, we generated all possible subsets and selected the one that resulted in the largest total value where the sums of the weights were less than or equal to W . To generate a more efficient approach, we use a dynamic programming approach. We can break the problem down into overlapping subproblems as follows: Consider the instance of the problem defined by first i items and a capacity j (j ≤ W ). Let V [i, j] be optimal value of such an instance, which is the value of an optimal solution consid- ering only the first i items that fit in a knapsack of capacity j. We can then solve it by considering two cases: the subproblem that includes the ith item, and the subproblem that does not. If we are not going to include the ith item, the optimal subset’s value (considering only items 0 through i − 1) would be V [i − 1, j]. If we do include item i (which is only possible if j −wi ≥ 0), its value is obtained from the optimal subset of the first i − 1 items that can fit within a capacity of j − wi , as vi + V [i − 1, j − wi ]. It’s also possible that the ith item does not fit (where j − w1 < 0), in which case the optimal subset is V [i − 1, j]. We can formulate these into a recurrence: max {V [i − 1, j], vi + V [i − 1, j − wi ]} if j − w1 ≥ 0 V [i, j] = V [i − 1, j] if j − wi < 0 Combine with some initial conditions: V [0, j] = 0 for j ≥ 0, V [i, 0] = 0 for i ≥ 0. The solution to our problem is the value V [n, W ]. The text has an example in Figure 8.13, where the solution is obtained in a “bottom up” fashion, filling in the table row by row or column by column, until we get our ultimate answer at in the lower right corner. This guarantees we will compute each subproblem exactly once and is clearly Θ(nW ) in time and space. One problem with that approach is the fact that we are computing some subproblems that will never be used in a recurrence starting from V [n, W ]. An alternate approach, this time working from the top (the solution) down (the subproblems), is to solve each subproblem as it’s needed. But...to avoid recomputing subproblems, we remember the answers to subproblems we have computed and just use them when they exist. 3
  • 4. CS 385 Analysis of Algorithms Spring 2011 The approach uses a technique called memory functions. These work just like regular functions, but do what we described above. At the start of the function, it looks to see if the requested instance has already been solved. If so, we just return the previously-computed result. If not, we compute it, save it in the table of answers in case it’s needed again, then return the answer. The following pseudocode implements this memory function idea for the knapsack problem: Globals: W[1..n]: item weights values[1..n]: item values V[0..n][0..W]: subproblem answers, starting all 0’s in first row/col, -1’s elsewhere mf_knapsack(i,j) if (V[i][j] < 0) if (j < W[i]) V[i][j] = mf_knapsack(i-1, j) else V[i][j] = max(mf_knapsack(i-1, j), values[i] + mf_knapsack(i-1, j-W[i])) return V[i][j] Applying this approach to the text’s example results in only 11 of the 20 values that were not initial conditions are computed, but only one value is reused. Larger instances would result in more subproblems being unneeded and more being reused. 4