Professional Documents
Culture Documents
Dynamic Programming (DP)
Dynamic Programming (DP)
PROGRAMMING dp
PHÂN TÍCH VÀ THIẾT KẾ THUẬT TOÁN
GIẢNG VIÊN: Nguyễn Thanh Sơn
CS112.L23.KHCL.N12
The shortest path
4
A D
1 11 18
2 5 13
S B E T
16 2
5
C F
2
Overlapping Subproblems
DP:
Optimal Substructure Property
5 6
def calculateFibonacciRecur(memoize, n):
if n < 2:
return n
#if we have already solved this subproblem, simply return the result from the cache
if memoize[n] >= 0:
return memoize[n]
f2 f1
3. Dynamic Programming Methods
Bottom-up with Tabulation
def CalculateFibonacci(int n)
{ f5
if (n==0) return 0;
int dp[] = new int[n+1];
f3 f4
//base cases
dp[0] = 0;
dp[1] = 1;
f1 f2 f2 f3
for(int i=2; i<=n; i++)
dp[i] = dp[i-1] + dp[i-2];
return dp[n]; f2 f1
}
Comparison
Must be solved from the top down Must be solved from the bottom up
Paradigm Methodology
Overlapping
Memoization
Subproblems
Top-down approach