KEMBAR78
Algorithm lecture Dynamic programming | PPT
Algorithms
Dynamic Programming
Dynamic Programming
• A strategy for designing algorithms is
dynamic programming
– A technique, not an algorithm
(like divide & conquer)
– The word “programming” is historical and
predates computer programming
• Use when problem breaks down into
recurring small subproblems
Dynamic Programming Example:
Longest Common Subsequence
• Longest common subsequence (LCS)
problem:
– Given two sequences x[1..m] and y[1..n], find
the longest subsequence which occurs in both
– Ex: x = {A B C B D A B }, y = {B D C A B A}
– {B C} and {A A} are both subsequences of both
– Brute-force algorithm: For every subsequence
of x, check if it’s a subsequence of y
LCS Algorithm
• Brute-force algorithm: 2m subsequences of
x to check against n elements of y:O(n 2m)
• Another example is finding nth Fibonacci
value.
• It can be solved three ways-
– Reursion
– Memoized
– DP
Fibonacci(Recursion)
int fib(int n)
{
if(memo[n] != null){
return memo[n]
}
if (n <= 1)
return n;
return fib(n-1) + fib(n-2);
}
Fibonacci(Memoized)
int fib(int n)
{
if(memo[n] != null){
return memo[n]
}
if (n <= 1)
result = 1
else{
result = fib(n-1) + fib(n-2);
}
fibo[n] = result;
return result;
}
Fibonacci(DP)
function fib(n) {
res[0] = 0;
res[1] = 1;
for(let i = 2; i <= n; i ++) {
res[i] = fibo[i - 1] + fibo[i - 2]
}
return return
}
The End

Algorithm lecture Dynamic programming

  • 1.
  • 2.
    Dynamic Programming • Astrategy for designing algorithms is dynamic programming – A technique, not an algorithm (like divide & conquer) – The word “programming” is historical and predates computer programming • Use when problem breaks down into recurring small subproblems
  • 3.
    Dynamic Programming Example: LongestCommon Subsequence • Longest common subsequence (LCS) problem: – Given two sequences x[1..m] and y[1..n], find the longest subsequence which occurs in both – Ex: x = {A B C B D A B }, y = {B D C A B A} – {B C} and {A A} are both subsequences of both – Brute-force algorithm: For every subsequence of x, check if it’s a subsequence of y
  • 4.
    LCS Algorithm • Brute-forcealgorithm: 2m subsequences of x to check against n elements of y:O(n 2m) • Another example is finding nth Fibonacci value. • It can be solved three ways- – Reursion – Memoized – DP
  • 5.
    Fibonacci(Recursion) int fib(int n) { if(memo[n]!= null){ return memo[n] } if (n <= 1) return n; return fib(n-1) + fib(n-2); }
  • 6.
    Fibonacci(Memoized) int fib(int n) { if(memo[n]!= null){ return memo[n] } if (n <= 1) result = 1 else{ result = fib(n-1) + fib(n-2); } fibo[n] = result; return result; }
  • 7.
    Fibonacci(DP) function fib(n) { res[0]= 0; res[1] = 1; for(let i = 2; i <= n; i ++) { res[i] = fibo[i - 1] + fibo[i - 2] } return return }
  • 8.