DP 1673149461
DP 1673149461
Programming
What is ?
2+2+2+2=? 2 2 2 2
Now, What is ?
2+2+2+2+2=? 2 2 2 2
8 2
We can arrive at the answer
super quickly -
10
As we already know the answer
to the previous question and by
just adding another 2,
itself.
That is f(n)=f(n-1)+2
f(n-1)=f(3)=6
And f(4)=f(3)+2=6+2=8
To solve this question through code, we have to first
values of n.
f(0)=0
f(1)=2
int count2(int n)
int f[n+1];
f[0]=0;
f[1]=2;
//iterate through 2 to n
for(int i=2;i<=n;i++)
f[i]=f[i-1]+2;
return f[n];
}
Complexity Analysis:
Complexity is O(n).
needed.
Dynamic programming vs Recursion
For Example
0 1
1
1 1
0,1,1,2,3,5,8……
int fib(int n)
if (n <= 1)
Recursion :
return n;
Exponential
return fib(n-l) + fib(n-2) ;
f[0] = 0;
f[1] = 1;
Dynamic
for (1 = 2; 1 <= n; i++)
Programming :
{
Linear
f[i] = f[i-1] + f[i-2];
return f(n];
If we use the recursive approach, it would take
exponential time for large values of n.
Tabulation
(n)!, you can store the previous products (n-1)! and just
multiply it with n.
Here you first calculate the values of f[0], f[1], f[2]..... And
int f[MAXN];
f[i] = f[i-1] * i;
Memoization
Memoization is a form of caching and is used to
optimise recursion.
If n== 0,
return 1
Else
Calculate (n−1)!×n
Return result
Algorithm
Dynamic Programming algorithm is designed using
the following four steps
Stair Proble
Pairing Proble
Two Dimensional D
Bitwise Dynamic Programming
Stair Problem:
For Example
Find out how many possible ways the person can run
up the stairs.
Algorithm:
1. Create a 1d array dp of size n+1
Complexity Analysis:
Pairing Problem:
Given the number of people to be ‘n’,every person can
either stay single or be paired with another person.
Each person can be paired only once.
For Example
n = 3
initialised.
f(0)=1
f(1)=1
f(2)=2
{ int countFriendsPairings(int n)
calculated values
//iterate through 3 to n
return f[n];
For Example
0 1 2 3
0 0
1 1
2 2
3 3
f(i,j)=f(i-1,j) + f(i,j-1)
f(i,j)=f(i-1,j) + f(i,j-1)
In this problem, the base cases are the first row (in
yellow) and leftmost column (in green).
All the cells in the first row can only be reached in one
way, by moving right from the cell to the left of them.
int countnoways(m,n)
f[0][0] = 1;
//base cases
//leftmost column
f[i][0] = 1;
//firstrow
f[0][ j] = 1;
[n-1]
Complexity Analysis:
Time Complexity: O(m*n)
https://www.geeksforgeeks.org/bitmasking-and-
dynamic-programming-set-1-count-ways-to-assign-
unique-cap-to-every-person/
https://bit.ly/2PIUjJp
→Number of ways to select n pairs of candies of
distinct colors
https://www.geeksforgeeks.org/count-ways-to-select-
n-pairs-of-candies-of-distinct-colors-dynamic-
programming-bitmasking/
https://bit.ly/3OycTiU
Must Do Problems in
Dynamic Programming :
9. Minimum Partition
in binary string
18. Largest Divisible Subset
19. Number of Submatrices That Sum to Target
20. Edit Distance
21. Interleaving String
22. Matrix Chain Multiplication