140 likes | 336 Views
Dynamic Programming. -動態規劃. Getting started : Fibonacci Sequence. Given initial value F(1) = 1, F(2) = 1. Recursive relation F(n) = F(n-1) + F(n-2) Given any number k, ask F(k). Fibonacci Sequence – Normal Solution. Use recursive Continuity call the previous one
E N D
Dynamic Programming -動態規劃
Getting started : Fibonacci Sequence • Given initial value F(1) = 1, F(2) = 1. • Recursive relation F(n) = F(n-1) + F(n-2) • Given any number k, ask F(k)
Fibonacci Sequence – Normal Solution • Use recursive • Continuity call the previous one • Return while it reach known value – F(1), F(2) + intuitive • Time-consuming and memory-consuming →How many counts needed?
Fibonacci Sequence – Another Way • Start from smaller one. • Continuous add the last two to get a new one. • Do until reach the value we want. + Faster - Not so easy to think at first glimpse
DP Elements • Table ElementDefinition • Recursive Formula • Computing Sequence • Recursion • Mathematical Induction • Divide-and-Conquer ※This part adapt from Pang-Feng’s PPT.
Relative Topics • LCS / LIS / .. • BFS / DFS • Back Tracking • Searching - More than once
Recall – LCS/LIS • Given two or more sequences. • Want to find the maximum length of common subsequence. • If add increasing restriction? • How about if we need to print the result out ?
Recall – BFS/DFS • Given a plane, may refine region or not. • Given starting point and ending point. • How many ways to reach with least steps? (Means how many different shortest paths?) • Visualize ? http://www.neopets.com/games/play.phtml?game_id=356
An example : Spilt coin • We have some values of coins now. $1, $5, … • Unlimited amount for each kind. • Given specific amount, find ways to combine. • How if there are many test cases ?
Direct thought : Top down • For example : $100, compose with $5 & $10 • We may take $5 or $10 from it. → So ways(100) = ways(100-5) + ways(100-10) → ways(n) = ways(n-5) + ways(n-10) • Use recursion until reach the known ones.
DP method : Bottom up • Consider the value we can form from lower one. • For example, if we have $5 and $10, we can add value by 5 or 10 through add one coin. • How to use it ?
Related Exercises on Uva OJ • 495 - Fibonacci Freeze • 825 - Walking on the Safe Side • 357 - Let Me Count The Ways • 10405 - Longest Common Subsequence • 111 - History Grading • 10684 - The jackpot • 105 - The Skyline Problem
References • Pangfeng Liu, ACP-DP, 2004, NTU • UVa Online Judge
Further Reading • BFS,DFS and backtracking, by yugi340238, 2009 -- Visualized illustration about search. • DP slider, by muming, 2009 -- Tiling problem, DP method of LIS. • DP slider, by geniusdog, 2008 -- Tiling problem, formal definition and properties about dynamic programming.