SlideShare ist ein Scribd-Unternehmen logo
1 von 36
Downloaden Sie, um offline zu lesen
Dynamic Programming
Jaehyun Park
CS 97SI
Stanford University
June 29, 2015
Outline
Dynamic Programming
1-dimensional DP
2-dimensional DP
Interval DP
Tree DP
Subset DP
Dynamic Programming 2
What is DP?
◮ Wikipedia definition: “method for solving complex problems
by breaking them down into simpler subproblems”
◮ This definition will make sense once we see some examples
– Actually, we’ll only see problem solving examples today
Dynamic Programming 3
Steps for Solving DP Problems
1. Define subproblems
2. Write down the recurrence that relates subproblems
3. Recognize and solve the base cases
◮ Each step is very important!
Dynamic Programming 4
Outline
Dynamic Programming
1-dimensional DP
2-dimensional DP
Interval DP
Tree DP
Subset DP
1-dimensional DP 5
1-dimensional DP Example
◮ Problem: given n, find the number of different ways to write
n as the sum of 1, 3, 4
◮ Example: for n = 5, the answer is 6
5 = 1 + 1 + 1 + 1 + 1
= 1 + 1 + 3
= 1 + 3 + 1
= 3 + 1 + 1
= 1 + 4
= 4 + 1
1-dimensional DP 6
1-dimensional DP Example
◮ Define subproblems
– Let Dn be the number of ways to write n as the sum of 1, 3, 4
◮ Find the recurrence
– Consider one possible solution n = x1 + x2 + · · · + xm
– If xm = 1, the rest of the terms must sum to n − 1
– Thus, the number of sums that end with xm = 1 is equal to
Dn−1
– Take other cases into account (xm = 3, xm = 4)
1-dimensional DP 7
1-dimensional DP Example
◮ Recurrence is then
Dn = Dn−1 + Dn−3 + Dn−4
◮ Solve the base cases
– D0 = 1
– Dn = 0 for all negative n
– Alternatively, can set: D0 = D1 = D2 = 1, and D3 = 2
◮ We’re basically done!
1-dimensional DP 8
Implementation
D[0] = D[1] = D[2] = 1; D[3] = 2;
for(i = 4; i <= n; i++)
D[i] = D[i-1] + D[i-3] + D[i-4];
◮ Very short!
◮ Extension: solving this for huge n, say n ≈ 1012
– Recall the matrix form of Fibonacci numbers
1-dimensional DP 9
POJ 2663: Tri Tiling
◮ Given n, find the number of ways to fill a 3 × n board with
dominoes
◮ Here is one possible solution for n = 12
1-dimensional DP 10
POJ 2663: Tri Tiling
◮ Define subproblems
– Define Dn as the number of ways to tile a 3 × n board
◮ Find recurrence
– Uuuhhhhh...
1-dimensional DP 11
Troll Tiling
1-dimensional DP 12
Defining Subproblems
◮ Obviously, the previous definition didn’t work very well
◮ Dn’s don’t relate in simple terms
◮ What if we introduce more subproblems?
1-dimensional DP 13
Defining Subproblems
1-dimensional DP 14
Finding Recurrences
1-dimensional DP 15
Finding Recurrences
◮ Consider different ways to fill the nth column
– And see what the remaining shape is
◮ Exercise:
– Finding recurrences for An, Bn, Cn
– Just for fun, why is Bn and En always zero?
◮ Extension: solving the problem for n × m grids, where n is
small, say n ≤ 10
– How many subproblems should we consider?
1-dimensional DP 16
Outline
Dynamic Programming
1-dimensional DP
2-dimensional DP
Interval DP
Tree DP
Subset DP
2-dimensional DP 17
2-dimensional DP Example
◮ Problem: given two strings x and y, find the longest common
subsequence (LCS) and print its length
◮ Example:
– x: ABCBDAB
– y: BDCABC
– “BCAB” is the longest subsequence found in both sequences, so
the answer is 4
2-dimensional DP 18
Solving the LCS Problem
◮ Define subproblems
– Let Dij be the length of the LCS of x1...i and y1...j
◮ Find the recurrence
– If xi = yj, they both contribute to the LCS
◮ Dij = Di−1,j−1 + 1
– Otherwise, either xi or yj does not contribute to the LCS, so
one can be dropped
◮ Dij = max{Di−1,j, Di,j−1}
– Find and solve the base cases: Di0 = D0j = 0
2-dimensional DP 19
Implementation
for(i = 0; i <= n; i++) D[i][0] = 0;
for(j = 0; j <= m; j++) D[0][j] = 0;
for(i = 1; i <= n; i++) {
for(j = 1; j <= m; j++) {
if(x[i] == y[j])
D[i][j] = D[i-1][j-1] + 1;
else
D[i][j] = max(D[i-1][j], D[i][j-1]);
}
}
2-dimensional DP 20
Outline
Dynamic Programming
1-dimensional DP
2-dimensional DP
Interval DP
Tree DP
Subset DP
Interval DP 21
Interval DP Example
◮ Problem: given a string x = x1...n, find the minimum number
of characters that need to be inserted to make it a palindrome
◮ Example:
– x: Ab3bd
– Can get “dAb3bAd” or “Adb3bdA” by inserting 2 characters
(one ‘d’, one ‘A’)
Interval DP 22
Interval DP Example
◮ Define subproblems
– Let Dij be the minimum number of characters that need to be
inserted to make xi...j into a palindrome
◮ Find the recurrence
– Consider a shortest palindrome y1...k containing xi...j
– Either y1 = xi or yk = xj (why?)
– y2...k−1 is then an optimal solution for xi+1...j or xi...j−1 or
xi+1...j−1
◮ Last case possible only if y1 = yk = xi = xj
Interval DP 23
Interval DP Example
◮ Find the recurrence
Dij =
1 + min{Di+1,j, Di,j−1} xi = xj
Di+1,j−1 xi = xj
◮ Find and solve the base cases: Dii = Di,i−1 = 0 for all i
◮ The entries of D must be filled in increasing order of j − i
Interval DP 24
Interval DP Example
// fill in base cases here
for(t = 2; t <= n; t++)
for(i = 1, j = t; j <= n; i++, j++)
// fill in D[i][j] here
◮ Note how we use an additional variable t to fill the table in
correct order
◮ And yes, for loops can work with multiple variables
Interval DP 25
An Alternate Solution
◮ Reverse x to get xR
◮ The answer is n − L, where L is the length of the LCS of x
and xR
◮ Exercise: Think about why this works
Interval DP 26
Outline
Dynamic Programming
1-dimensional DP
2-dimensional DP
Interval DP
Tree DP
Subset DP
Tree DP 27
Tree DP Example
◮ Problem: given a tree, color nodes black as many as possible
without coloring two adjacent nodes
◮ Subproblems:
– First, we arbitrarily decide the root node r
– Bv: the optimal solution for a subtree having v as the root,
where we color v black
– Wv: the optimal solution for a subtree having v as the root,
where we don’t color v
– Answer is max{Br, Wr}
Tree DP 28
Tree DP Example
◮ Find the recurrence
– Crucial observation: once v’s color is determined, subtrees can
be solved independently
– If v is colored, its children must not be colored
Bv = 1 +
u∈children(v)
Wu
– If v is not colored, its children can have any color
Wv = 1 +
u∈children(v)
max{Bu, Wu}
◮ Base cases: leaf nodes
Tree DP 29
Outline
Dynamic Programming
1-dimensional DP
2-dimensional DP
Interval DP
Tree DP
Subset DP
Subset DP 30
Subset DP Example
◮ Problem: given a weighted graph with n nodes, find the
shortest path that visits every node exactly once (Traveling
Salesman Problem)
◮ Wait, isn’t this an NP-hard problem?
– Yes, but we can solve it in O(n2
2n
) time
– Note: brute force algorithm takes O(n!) time
Subset DP 31
Subset DP Example
◮ Define subproblems
– DS,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 DV,v, where V is the given set of nodes
◮ Let’s solve the base cases first
– For each node v, D{v},v = 0
Subset DP 32
Subset DP Example
◮ Find the recurrence
– 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
DS,v = min
u∈S−{v}
DS−{v},u + cost(u, v)
Subset DP 33
Working with Subsets
◮ When working with subsets, it’s good to have a nice
representation of sets
◮ Idea: Use an integer to represent a set
– Concise representation of subsets of small integers {0, 1, . . .}
– If the ith (least significant) digit is 1, i is in the set
– If the ith digit is 0, i is not in the set
– e.g., 19 = 010011(2) in binary represent a set {0, 1, 4}
Subset DP 34
Using Bitmasks
◮ Union of two sets x and y: x | y
◮ Intersection: x & y
◮ Symmetric difference: x ˆ y
◮ Singleton set {i}: 1 << i
◮ Membership test: x & (1 << i) != 0
Subset DP 35
Conclusion
◮ Wikipedia definition: “a method for solving complex problems
by breaking them down into simpler subproblems”
– Does this make sense now?
◮ Remember the three steps!
1. Defining subproblems
2. Finding recurrences
3. Solving the base cases
Subset DP 36

Weitere ähnliche Inhalte

Was ist angesagt?

Csr2011 june14 09_30_grigoriev
Csr2011 june14 09_30_grigorievCsr2011 june14 09_30_grigoriev
Csr2011 june14 09_30_grigoriev
CSR2011
 
Magic graphs
Magic graphsMagic graphs
Magic graphs
Springer
 

Was ist angesagt? (20)

1508.07756v1
1508.07756v11508.07756v1
1508.07756v1
 
Permutations and Combinations IIT JEE+Olympiad Lecture 4
Permutations and Combinations IIT JEE+Olympiad Lecture 4Permutations and Combinations IIT JEE+Olympiad Lecture 4
Permutations and Combinations IIT JEE+Olympiad Lecture 4
 
Classifying Polynomials
Classifying PolynomialsClassifying Polynomials
Classifying Polynomials
 
Arithmetic progression
Arithmetic progressionArithmetic progression
Arithmetic progression
 
Ch4 Polynomials
Ch4 PolynomialsCh4 Polynomials
Ch4 Polynomials
 
Dividing Polynomials Slide Share
Dividing Polynomials Slide ShareDividing Polynomials Slide Share
Dividing Polynomials Slide Share
 
Backtracking
BacktrackingBacktracking
Backtracking
 
Csr2011 june14 09_30_grigoriev
Csr2011 june14 09_30_grigorievCsr2011 june14 09_30_grigoriev
Csr2011 june14 09_30_grigoriev
 
Csr2011 june14 09_30_grigoriev
Csr2011 june14 09_30_grigorievCsr2011 june14 09_30_grigoriev
Csr2011 june14 09_30_grigoriev
 
235limit
235limit235limit
235limit
 
Magic graphs
Magic graphsMagic graphs
Magic graphs
 
On the Secrecy of RSA Private Keys
On the Secrecy of RSA Private KeysOn the Secrecy of RSA Private Keys
On the Secrecy of RSA Private Keys
 
Integration presentation
Integration presentationIntegration presentation
Integration presentation
 
Decision Trees and Bayes Classifiers
Decision Trees and Bayes ClassifiersDecision Trees and Bayes Classifiers
Decision Trees and Bayes Classifiers
 
Bca1040 digital logic
Bca1040   digital logicBca1040   digital logic
Bca1040 digital logic
 
11.2
11.211.2
11.2
 
Polynomials
PolynomialsPolynomials
Polynomials
 
Arithmetic Progression - $@mEe
Arithmetic Progression - $@mEeArithmetic Progression - $@mEe
Arithmetic Progression - $@mEe
 
Ch08
Ch08Ch08
Ch08
 
Polynomials
PolynomialsPolynomials
Polynomials
 

Ähnlich wie Dynamic programming

20101017 program analysis_for_security_livshits_lecture02_compilers
20101017 program analysis_for_security_livshits_lecture02_compilers20101017 program analysis_for_security_livshits_lecture02_compilers
20101017 program analysis_for_security_livshits_lecture02_compilers
Computer Science Club
 
Signal processingcolumbia
Signal processingcolumbiaSignal processingcolumbia
Signal processingcolumbia
vevin1986
 
Divide-and-Conquer & Dynamic ProgrammingDivide-and-Conqu.docx
Divide-and-Conquer & Dynamic ProgrammingDivide-and-Conqu.docxDivide-and-Conquer & Dynamic ProgrammingDivide-and-Conqu.docx
Divide-and-Conquer & Dynamic ProgrammingDivide-and-Conqu.docx
jacksnathalie
 
C2 st lecture 4 handout
C2 st lecture 4 handoutC2 st lecture 4 handout
C2 st lecture 4 handout
fatima d
 
Calculus 08 techniques_of_integration
Calculus 08 techniques_of_integrationCalculus 08 techniques_of_integration
Calculus 08 techniques_of_integration
tutulk
 
Lesson 19: Optimization Problems
Lesson 19: Optimization ProblemsLesson 19: Optimization Problems
Lesson 19: Optimization Problems
Matthew Leingang
 
November 3, 2014
November 3, 2014November 3, 2014
November 3, 2014
khyps13
 

Ähnlich wie Dynamic programming (20)

04 greedyalgorithmsii 2x2
04 greedyalgorithmsii 2x204 greedyalgorithmsii 2x2
04 greedyalgorithmsii 2x2
 
Dynamic Programming.pptx
Dynamic Programming.pptxDynamic Programming.pptx
Dynamic Programming.pptx
 
Advance algebra
Advance algebraAdvance algebra
Advance algebra
 
20101017 program analysis_for_security_livshits_lecture02_compilers
20101017 program analysis_for_security_livshits_lecture02_compilers20101017 program analysis_for_security_livshits_lecture02_compilers
20101017 program analysis_for_security_livshits_lecture02_compilers
 
dynamic programming Rod cutting class
dynamic programming Rod cutting classdynamic programming Rod cutting class
dynamic programming Rod cutting class
 
dynamic-programming
dynamic-programmingdynamic-programming
dynamic-programming
 
Signal processingcolumbia
Signal processingcolumbiaSignal processingcolumbia
Signal processingcolumbia
 
Divide-and-Conquer & Dynamic ProgrammingDivide-and-Conqu.docx
Divide-and-Conquer & Dynamic ProgrammingDivide-and-Conqu.docxDivide-and-Conquer & Dynamic ProgrammingDivide-and-Conqu.docx
Divide-and-Conquer & Dynamic ProgrammingDivide-and-Conqu.docx
 
Duality in Linear Programming Problem
Duality in Linear Programming ProblemDuality in Linear Programming Problem
Duality in Linear Programming Problem
 
C2 st lecture 4 handout
C2 st lecture 4 handoutC2 st lecture 4 handout
C2 st lecture 4 handout
 
Calculus 08 techniques_of_integration
Calculus 08 techniques_of_integrationCalculus 08 techniques_of_integration
Calculus 08 techniques_of_integration
 
Theory of Computation Introduction Session
Theory of Computation Introduction SessionTheory of Computation Introduction Session
Theory of Computation Introduction Session
 
Lesson 19: Optimization Problems
Lesson 19: Optimization ProblemsLesson 19: Optimization Problems
Lesson 19: Optimization Problems
 
AAC ch 3 Advance strategies (Dynamic Programming).pptx
AAC ch 3 Advance strategies (Dynamic Programming).pptxAAC ch 3 Advance strategies (Dynamic Programming).pptx
AAC ch 3 Advance strategies (Dynamic Programming).pptx
 
Proof Techniques
Proof TechniquesProof Techniques
Proof Techniques
 
Divide and Conquer
Divide and ConquerDivide and Conquer
Divide and Conquer
 
Imc2020 day1&amp;2 problems&amp;solutions
Imc2020 day1&amp;2 problems&amp;solutionsImc2020 day1&amp;2 problems&amp;solutions
Imc2020 day1&amp;2 problems&amp;solutions
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Core 2 indefinite integration
Core 2 indefinite integrationCore 2 indefinite integration
Core 2 indefinite integration
 
November 3, 2014
November 3, 2014November 3, 2014
November 3, 2014
 

Mehr von Nguyễn Anh

Báo cáo đồ họa máy tính - Computer graphics
Báo cáo đồ họa máy tính - Computer graphicsBáo cáo đồ họa máy tính - Computer graphics
Báo cáo đồ họa máy tính - Computer graphics
Nguyễn Anh
 

Mehr von Nguyễn Anh (20)

Báo cáo đồ họa máy tính - Computer graphics
Báo cáo đồ họa máy tính - Computer graphicsBáo cáo đồ họa máy tính - Computer graphics
Báo cáo đồ họa máy tính - Computer graphics
 
Game programming - Hexagon
Game programming - HexagonGame programming - Hexagon
Game programming - Hexagon
 
Nghiên cứu chuẩn ISO/IEC 9126 trong đánh giá chất lượng phần mềm
Nghiên cứu chuẩn ISO/IEC 9126 trong đánh giá chất lượng phần mềmNghiên cứu chuẩn ISO/IEC 9126 trong đánh giá chất lượng phần mềm
Nghiên cứu chuẩn ISO/IEC 9126 trong đánh giá chất lượng phần mềm
 
Ứng dụng ngôn ngữ UML trong phân tích và thiết kế website cho giảng viên Việ...
Ứng dụng ngôn ngữ UML trong phân tích và thiết kế  website cho giảng viên Việ...Ứng dụng ngôn ngữ UML trong phân tích và thiết kế  website cho giảng viên Việ...
Ứng dụng ngôn ngữ UML trong phân tích và thiết kế website cho giảng viên Việ...
 
Tìm hiểu các kỹ thuật kiểm thử phần mềm ứng dụng trong lập trình Java.
Tìm hiểu các kỹ thuật kiểm thử phần mềm  ứng dụng trong lập trình Java.Tìm hiểu các kỹ thuật kiểm thử phần mềm  ứng dụng trong lập trình Java.
Tìm hiểu các kỹ thuật kiểm thử phần mềm ứng dụng trong lập trình Java.
 
Sldie TÌM HIỂU CÁC KỸ THUẬT KIỂM THỬ PHẦN MỀM
Sldie TÌM HIỂU CÁC KỸ THUẬT KIỂM THỬ PHẦN MỀMSldie TÌM HIỂU CÁC KỸ THUẬT KIỂM THỬ PHẦN MỀM
Sldie TÌM HIỂU CÁC KỸ THUẬT KIỂM THỬ PHẦN MỀM
 
TÌM HIỂU CÁC KỸ THUẬT KIỂM THỬ PHẦN MỀM
TÌM HIỂU CÁC KỸ THUẬT KIỂM THỬ PHẦN MỀMTÌM HIỂU CÁC KỸ THUẬT KIỂM THỬ PHẦN MỀM
TÌM HIỂU CÁC KỸ THUẬT KIỂM THỬ PHẦN MỀM
 
Tìm Hiểu Các Kỹ Thuật Kiểm Thử Phần Mềm và Một Số Ứng Dụng Trong Thực Tế
Tìm Hiểu Các Kỹ Thuật Kiểm Thử Phần Mềm và Một Số Ứng Dụng Trong Thực Tế Tìm Hiểu Các Kỹ Thuật Kiểm Thử Phần Mềm và Một Số Ứng Dụng Trong Thực Tế
Tìm Hiểu Các Kỹ Thuật Kiểm Thử Phần Mềm và Một Số Ứng Dụng Trong Thực Tế
 
Tìm hiểu về kỹ thuật Kiểm thử phần mềm
Tìm hiểu về kỹ thuật Kiểm thử phần mềmTìm hiểu về kỹ thuật Kiểm thử phần mềm
Tìm hiểu về kỹ thuật Kiểm thử phần mềm
 
Bảo trì phần mềm
Bảo trì phần mềmBảo trì phần mềm
Bảo trì phần mềm
 
Embedded beta2 new
Embedded beta2 newEmbedded beta2 new
Embedded beta2 new
 
Embedded linux edited
Embedded linux editedEmbedded linux edited
Embedded linux edited
 
Slide Các kỹ thuật bảo trì phần mềm
Slide Các kỹ thuật bảo trì phần mềmSlide Các kỹ thuật bảo trì phần mềm
Slide Các kỹ thuật bảo trì phần mềm
 
Các kỹ thuật bảo trì phần mềm
Các kỹ thuật bảo trì phần mềmCác kỹ thuật bảo trì phần mềm
Các kỹ thuật bảo trì phần mềm
 
TÌM HIỂU CÁC KỸ THUẬT KIỂM THỬ PHẦN MỀM
TÌM HIỂU CÁC KỸ THUẬT KIỂM THỬ PHẦN MỀMTÌM HIỂU CÁC KỸ THUẬT KIỂM THỬ PHẦN MỀM
TÌM HIỂU CÁC KỸ THUẬT KIỂM THỬ PHẦN MỀM
 
Đào tạo ĐH
Đào tạo ĐHĐào tạo ĐH
Đào tạo ĐH
 
Cài đặt windows mà không cần phải kích hoạt
Cài đặt  windows mà không cần phải kích hoạtCài đặt  windows mà không cần phải kích hoạt
Cài đặt windows mà không cần phải kích hoạt
 
System hacking
System hackingSystem hacking
System hacking
 
Hoc internet
Hoc internetHoc internet
Hoc internet
 
Cach setup bios
Cach setup biosCach setup bios
Cach setup bios
 

Kürzlich hochgeladen

VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
dollysharma2066
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
ankushspencer015
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Kürzlich hochgeladen (20)

KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
Intro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdfIntro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdf
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 

Dynamic programming

  • 1. Dynamic Programming Jaehyun Park CS 97SI Stanford University June 29, 2015
  • 2. Outline Dynamic Programming 1-dimensional DP 2-dimensional DP Interval DP Tree DP Subset DP Dynamic Programming 2
  • 3. What is DP? ◮ Wikipedia definition: “method for solving complex problems by breaking them down into simpler subproblems” ◮ This definition will make sense once we see some examples – Actually, we’ll only see problem solving examples today Dynamic Programming 3
  • 4. Steps for Solving DP Problems 1. Define subproblems 2. Write down the recurrence that relates subproblems 3. Recognize and solve the base cases ◮ Each step is very important! Dynamic Programming 4
  • 5. Outline Dynamic Programming 1-dimensional DP 2-dimensional DP Interval DP Tree DP Subset DP 1-dimensional DP 5
  • 6. 1-dimensional DP Example ◮ Problem: given n, find the number of different ways to write n as the sum of 1, 3, 4 ◮ Example: for n = 5, the answer is 6 5 = 1 + 1 + 1 + 1 + 1 = 1 + 1 + 3 = 1 + 3 + 1 = 3 + 1 + 1 = 1 + 4 = 4 + 1 1-dimensional DP 6
  • 7. 1-dimensional DP Example ◮ Define subproblems – Let Dn be the number of ways to write n as the sum of 1, 3, 4 ◮ Find the recurrence – Consider one possible solution n = x1 + x2 + · · · + xm – If xm = 1, the rest of the terms must sum to n − 1 – Thus, the number of sums that end with xm = 1 is equal to Dn−1 – Take other cases into account (xm = 3, xm = 4) 1-dimensional DP 7
  • 8. 1-dimensional DP Example ◮ Recurrence is then Dn = Dn−1 + Dn−3 + Dn−4 ◮ Solve the base cases – D0 = 1 – Dn = 0 for all negative n – Alternatively, can set: D0 = D1 = D2 = 1, and D3 = 2 ◮ We’re basically done! 1-dimensional DP 8
  • 9. Implementation D[0] = D[1] = D[2] = 1; D[3] = 2; for(i = 4; i <= n; i++) D[i] = D[i-1] + D[i-3] + D[i-4]; ◮ Very short! ◮ Extension: solving this for huge n, say n ≈ 1012 – Recall the matrix form of Fibonacci numbers 1-dimensional DP 9
  • 10. POJ 2663: Tri Tiling ◮ Given n, find the number of ways to fill a 3 × n board with dominoes ◮ Here is one possible solution for n = 12 1-dimensional DP 10
  • 11. POJ 2663: Tri Tiling ◮ Define subproblems – Define Dn as the number of ways to tile a 3 × n board ◮ Find recurrence – Uuuhhhhh... 1-dimensional DP 11
  • 13. Defining Subproblems ◮ Obviously, the previous definition didn’t work very well ◮ Dn’s don’t relate in simple terms ◮ What if we introduce more subproblems? 1-dimensional DP 13
  • 16. Finding Recurrences ◮ Consider different ways to fill the nth column – And see what the remaining shape is ◮ Exercise: – Finding recurrences for An, Bn, Cn – Just for fun, why is Bn and En always zero? ◮ Extension: solving the problem for n × m grids, where n is small, say n ≤ 10 – How many subproblems should we consider? 1-dimensional DP 16
  • 17. Outline Dynamic Programming 1-dimensional DP 2-dimensional DP Interval DP Tree DP Subset DP 2-dimensional DP 17
  • 18. 2-dimensional DP Example ◮ Problem: given two strings x and y, find the longest common subsequence (LCS) and print its length ◮ Example: – x: ABCBDAB – y: BDCABC – “BCAB” is the longest subsequence found in both sequences, so the answer is 4 2-dimensional DP 18
  • 19. Solving the LCS Problem ◮ Define subproblems – Let Dij be the length of the LCS of x1...i and y1...j ◮ Find the recurrence – If xi = yj, they both contribute to the LCS ◮ Dij = Di−1,j−1 + 1 – Otherwise, either xi or yj does not contribute to the LCS, so one can be dropped ◮ Dij = max{Di−1,j, Di,j−1} – Find and solve the base cases: Di0 = D0j = 0 2-dimensional DP 19
  • 20. Implementation for(i = 0; i <= n; i++) D[i][0] = 0; for(j = 0; j <= m; j++) D[0][j] = 0; for(i = 1; i <= n; i++) { for(j = 1; j <= m; j++) { if(x[i] == y[j]) D[i][j] = D[i-1][j-1] + 1; else D[i][j] = max(D[i-1][j], D[i][j-1]); } } 2-dimensional DP 20
  • 21. Outline Dynamic Programming 1-dimensional DP 2-dimensional DP Interval DP Tree DP Subset DP Interval DP 21
  • 22. Interval DP Example ◮ Problem: given a string x = x1...n, find the minimum number of characters that need to be inserted to make it a palindrome ◮ Example: – x: Ab3bd – Can get “dAb3bAd” or “Adb3bdA” by inserting 2 characters (one ‘d’, one ‘A’) Interval DP 22
  • 23. Interval DP Example ◮ Define subproblems – Let Dij be the minimum number of characters that need to be inserted to make xi...j into a palindrome ◮ Find the recurrence – Consider a shortest palindrome y1...k containing xi...j – Either y1 = xi or yk = xj (why?) – y2...k−1 is then an optimal solution for xi+1...j or xi...j−1 or xi+1...j−1 ◮ Last case possible only if y1 = yk = xi = xj Interval DP 23
  • 24. Interval DP Example ◮ Find the recurrence Dij = 1 + min{Di+1,j, Di,j−1} xi = xj Di+1,j−1 xi = xj ◮ Find and solve the base cases: Dii = Di,i−1 = 0 for all i ◮ The entries of D must be filled in increasing order of j − i Interval DP 24
  • 25. Interval DP Example // fill in base cases here for(t = 2; t <= n; t++) for(i = 1, j = t; j <= n; i++, j++) // fill in D[i][j] here ◮ Note how we use an additional variable t to fill the table in correct order ◮ And yes, for loops can work with multiple variables Interval DP 25
  • 26. An Alternate Solution ◮ Reverse x to get xR ◮ The answer is n − L, where L is the length of the LCS of x and xR ◮ Exercise: Think about why this works Interval DP 26
  • 27. Outline Dynamic Programming 1-dimensional DP 2-dimensional DP Interval DP Tree DP Subset DP Tree DP 27
  • 28. Tree DP Example ◮ Problem: given a tree, color nodes black as many as possible without coloring two adjacent nodes ◮ Subproblems: – First, we arbitrarily decide the root node r – Bv: the optimal solution for a subtree having v as the root, where we color v black – Wv: the optimal solution for a subtree having v as the root, where we don’t color v – Answer is max{Br, Wr} Tree DP 28
  • 29. Tree DP Example ◮ Find the recurrence – Crucial observation: once v’s color is determined, subtrees can be solved independently – If v is colored, its children must not be colored Bv = 1 + u∈children(v) Wu – If v is not colored, its children can have any color Wv = 1 + u∈children(v) max{Bu, Wu} ◮ Base cases: leaf nodes Tree DP 29
  • 30. Outline Dynamic Programming 1-dimensional DP 2-dimensional DP Interval DP Tree DP Subset DP Subset DP 30
  • 31. Subset DP Example ◮ Problem: given a weighted graph with n nodes, find the shortest path that visits every node exactly once (Traveling Salesman Problem) ◮ Wait, isn’t this an NP-hard problem? – Yes, but we can solve it in O(n2 2n ) time – Note: brute force algorithm takes O(n!) time Subset DP 31
  • 32. Subset DP Example ◮ Define subproblems – DS,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 DV,v, where V is the given set of nodes ◮ Let’s solve the base cases first – For each node v, D{v},v = 0 Subset DP 32
  • 33. Subset DP Example ◮ Find the recurrence – 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 DS,v = min u∈S−{v} DS−{v},u + cost(u, v) Subset DP 33
  • 34. Working with Subsets ◮ When working with subsets, it’s good to have a nice representation of sets ◮ Idea: Use an integer to represent a set – Concise representation of subsets of small integers {0, 1, . . .} – If the ith (least significant) digit is 1, i is in the set – If the ith digit is 0, i is not in the set – e.g., 19 = 010011(2) in binary represent a set {0, 1, 4} Subset DP 34
  • 35. Using Bitmasks ◮ Union of two sets x and y: x | y ◮ Intersection: x & y ◮ Symmetric difference: x ˆ y ◮ Singleton set {i}: 1 << i ◮ Membership test: x & (1 << i) != 0 Subset DP 35
  • 36. Conclusion ◮ Wikipedia definition: “a method for solving complex problems by breaking them down into simpler subproblems” – Does this make sense now? ◮ Remember the three steps! 1. Defining subproblems 2. Finding recurrences 3. Solving the base cases Subset DP 36