Compute Total Number of Distinct Ways to Reach Target

Customer Support: admin@thealgorists.com

Feedback:
We are listening to your every feedback,
and taking action to constantly improve your learning experience.
If you have any feedback, please use this form:
https://thealgorists.com/Feedback.
 If you are a student, email to admin@thealgorists.com to get special student discount.
The DP problems belonging to this category, in its simplest form, looks like below or some variation of it:
 Given a target find a number of distinct ways to reach the target.
The solution for this kind of problems, in a generalized form, would often look like below:

Sum all possible ways to reach the current state.
distinctWays[i] = distinctWays[i1] + distinctWays[i2] + ... + distinctWays[ik]
, where (i  1), (i  2), ... , (i  K) are all the directly immediate states from where i can be reached. 
Overall the solution would look like:
for (int curr = 1; curr <= target; curr++) { for (int k = 0; k < waysToReachCurrentTarget.size(); k++) { dp[i] += dp[waysToReachCurrentTarget[k]]; } } return dp[target];
The below problem would give you a basic idea about this kind of problems:
Problem Statement:
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
Solution:
class Solution {
// DP with O(n) space
public int climbStairs(int n) {
if (n == 0) {
return 0;
}
int[] dp = new int[n];
for (int i = 0; i < n; i++) {
if (i < 2) {
dp[i] = i + 1;
} else {
dp[i] = dp[i  2] + dp[i  1];
}
}
return dp[n  1];
}
}
class Solution {
// DP with O(1) space
public int climbStairs(int n) {
if (n < 3) {
return n;
}
int a = 1;
int b = 2;
int c = 0;
for (int i = 2; i < n; i++) {
c = a + b;
a = b;
b = c;
}
return c;
}
}
The above content is written by:
Abhishek Dey
A Visionary Software Engineer With A Mission To Empower Every Person & Every Organization On The Planet To Achieve More
Microsoft  University of Florida
If you have any feedback, please use this form: https://thealgorists.com/Feedback.
Follow Us On LinkedIn