Dynamic Programming (Part 2) Framework for Solving DP Prolems (Climbing Stairs, Unique Paths)
This is the follow-up for the last tutorial. I will show you how to cope with Dynamic Programming problems.
Advantages
Addresses problems with exponantial time complexity to Polynomial (sometimes even linear)
$O(c^n)$ -> $O(n^c)$ -> $O(n)$
When to Use
When we don’t want to recalculate things. We want to rely on existing solutions.
Requirments
Properties
- Optimal Substructure
Use $X_1$ to solve $X_2$ to solve $X_3$ etc. to solve the entire problem.
- Overlapping Subprolems
Fibonacci
$Fib(5) = Fib(4) + Fib(3)$
$Fib(4) = Fib(3) + Fib(2)$
…
Overlapping part: $Fib(3)$, $Fib(2)$, $Fib(1)$ (Memoized/Cached Results)
Types of Problems
- Combinatoric -> Ans: How many…?
- Optimization -> Ans: Minimum/Maximum of steps/ways/paths…
$$1+2+3+4+5+…+R=\sum_{i=1}^n i$$
$n=1$, $F(1)=1$
$n=2$, $F(2)=F(1)+2=3$
$n=3$, $F(3)=F(2)+3=6$
…
$F(n)=F(n-1)+n$
Go Implementation
|
|
Framework for Solving DP Problems
- Express our goal as an objective functions
Example: Climbing Stairs Problem
$F(i)$ is the number of distinct ways to reach the i-th stair 2. Identify Base cases (to solve bondary problems)
$F(2)=2$
$F(1)=1$
$F(0)=1$
$$F(n)=F(n-1)+F(n-2)$$
- Recurrence relation
- Order of computation
- Location of the answer
$F(n)$
LeetCode Example
Unique Paths
[Medium]
There is a robot on an m x n
grid. The robot is initially located at the top-left corner (i.e., grid[0][0]
). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]
). The robot can only move either down or right at any point in time.
Given the two integers m
and n
, return the number of possible unique paths that the robot can take to reach the bottom-right corner.
The test cases are generated so that the answer will be less than or equal to 2 * 109
.
Example 1:
Input: m = 3, n = 7
Output: 28
Example 2:
Input: m = 3, n = 2
Output: 3
Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
- Right -> Down -> Down
- Down -> Down -> Right
- Down -> Right -> Down
Constraints:
1 <= m, n <= 100
Code
First Approach
|
|
Second Approach (Optimized)
|
|