Given an integer N, representing the number of stations lying between the source and the destination. There are three trains available from every station and their stoppage patterns are as follows:
- Train 1: Stops at every station
- Train 2: Stops at every alternate station
- Train 3: Stops at every third station
The task is to find the number of ways to reach the destination from the source using any possible combination of trains.
Examples:
Input: N = 2Â
Output: 4
Explanation:Â
Four possible ways exists to travel from source to destination with 2 stations in between:
Train 1 (from source) -> Train 1 (from station 1) -> Train 1(from station 2) -> Destination
Train 2 (from source) -> Train 1 (from station 2) -> Destination
Train 1 (from source) -> Train 2 (from station 1) -> Destination
Train 3 (from source) -> DestinationInput: N = 0
Output: 1
Explanation: No station is present in between the source and destination. Therefore, there is only one way to travel, i.e.
Train 1(from source) -> Destination
Approach: The main idea to solve the problem is to use Recursion with Memoization to solve this problem. The recurrence relation is as follows:
 F(N) = F(N – 1) + F(N – 2) + F(N – 3),
where,
F(N – 1) counts ways to travel upto (N – 1)th station.
F(N – 2) counts ways to travel upto (N – 2)th station.
F(N – 3) counts ways to travel upto (N – 3)th station.
Follow the steps below to solve the problem:
- Initialize an array dp[] for memorization. Set all indices to -1 initially.
- Define a recursive function findWays() to calculate the number of ways to reach the Nth station.
- Following base cases are required to be considered:
- For x < 0 return 0.
- For x = 0, return 1.
- For x = 1, return 2.
- For x = 2, return 4.
- If the current state, say x, is already evaluated i.e. dp[x] is not equal to -1, simply return the evaluated value.
- Otherwise, calculate findWays(x – 1), findWays(x – 2) and findWays(x – 3) recursively and store their sum in dp[x].
- Return dp[x].
Below is the implementation of the above approach:
C++14
// C++ program of the above approach#include <bits/stdc++.h>using namespace std;Â
// Dp table for memoizationint dp[100000];Â
// Function to count the number// of ways to N-th stationint findWays(int x){    // Base Cases    if (x < 0)        return 0;Â
    if (x == 0)        return 1;Â
    if (x == 1)        return 2;Â
    if (x == 2)        return 4;Â
    // If current state is    // already evaluated    if (dp[x] != -1)        return dp[x];Â
    // Recursive callsÂ
    // Count ways in which    // train 1 can be chosen    int count = findWays(x - 1);Â
    // Count ways in which    // train 2 can be chosen    count += findWays(x - 2);Â
    // Count ways in which    // train 3 can be chosen    count += findWays(x - 3);Â
    // Store the current state    dp[x] = count;Â
    // Return the number of ways    return dp[x];}Â
// Driver Codeint main(){Â
    // Given Input    int n = 4;Â
    // Initialize DP table with -1    memset(dp, -1, sizeof(dp));Â
    // Function call to count    // the number of ways to    // reach the n-th station    cout << findWays(n) << "\n";} |
Java
// Java program for the above approachimport java.util.*;class GFG{Â
  // Dp table for memoization  static int dp[] = new int[100000];Â
  // Function to count the number  // of ways to N-th station  static int findWays(int x)  {Â
    // Base Cases    if (x < 0)      return 0;Â
    if (x == 0)      return 1;Â
    if (x == 1)      return 2;Â
    if (x == 2)      return 4;Â
    // If current state is    // already evaluated    if (dp[x] != -1)      return dp[x];Â
    // Recursive callsÂ
    // Count ways in which    // train 1 can be chosen    int count = findWays(x - 1);Â
    // Count ways in which    // train 2 can be chosen    count += findWays(x - 2);Â
    // Count ways in which    // train 3 can be chosen    count += findWays(x - 3);Â
    // Store the current state    dp[x] = count;Â
    // Return the number of ways    return dp[x];  }Â
  // Driven Code  public static void main(String[] args)  {Â
    // Given Input    int n = 4;Â
    // Initialize DP table with -1    Arrays.fill(dp, -1);Â
    // Function call to count    // the number of ways to    // reach the n-th station    System.out.print(findWays(n));  }}Â
// This code is contributed by splevel62. |
Python3
# Python3 program of the above approachÂ
# Dp table for memoizationdp = [-1 for i in range(100000)]Â
# Function to count the number# of ways to N-th stationdef findWays(x):         # Base Cases    if (x < 0):        return 0Â
    if (x == 0):        return 1Â
    if (x == 1):        return 2Â
    if (x == 2):        return 4Â
    # If current state is    # already evaluated    if (dp[x] != -1):        return dp[x]Â
    # Recursive callsÂ
    # Count ways in which    # train 1 can be chosen    count = findWays(x - 1)Â
    # Count ways in which    # train 2 can be chosen    count += findWays(x - 2)Â
    # Count ways in which    # train 3 can be chosen    count += findWays(x - 3)Â
    # Store the current state    dp[x] = countÂ
    # Return the number of ways    return dp[x]Â
# Driver Codeif __name__ == '__main__':         # Given Input    n = 4         # Function call to count    # the number of ways to    # reach the n-th station    print(findWays(n))Â
# This code is contributed by SURENDRA_GANGWAR |
C#
// C# program to implement above approachusing System;using System.Collections.Generic;Â
class GFG{Â
  // Dp table for memoization  static int[] dp = new int[100000];Â
  // Function to count the number  // of ways to N-th station  static int findWays(int x)  {    // Base Cases    if (x < 0)      return 0;Â
    if (x == 0)      return 1;Â
    if (x == 1)      return 2;Â
    if (x == 2)      return 4;Â
    // If current state is    // already evaluated    if (dp[x] != -1)      return dp[x];Â
    // Recursive callsÂ
    // Count ways in which    // train 1 can be chosen    int count = findWays(x - 1);Â
    // Count ways in which    // train 2 can be chosen    count += findWays(x - 2);Â
    // Count ways in which    // train 3 can be chosen    count += findWays(x - 3);Â
    // Store the current state    dp[x] = count;Â
    // Return the number of ways    return dp[x];  }Â
  // Driver Code  public static void Main(string[] args){Â
    // Given Input    int n = 4;Â
    // Initialize DP table with -1    for(int i = 0 ; i < dp.Length ; i++){      dp[i] = -1;    }Â
    // Function call to count    // the number of ways to    // reach the n-th station    Console.Write(findWays(n) + "\n");Â
  }}Â
// This code is contributed by subhamgoyal2014. |
Javascript
<script>Â
// JavaScript program of the above approachÂ
// Dp table for memoizationlet dp = new Array(100000).fill(-1)Â
// Function to count the number// of ways to N-th stationfunction findWays(x){         // Base Cases    if (x < 0)        return 0Â
    if (x == 0)        return 1Â
    if (x == 1)        return 2Â
    if (x == 2)        return 4Â
    // If current state is    // already evaluated    if (dp[x] != -1)        return dp[x]Â
    // Recursive callsÂ
    // Count ways in which    // train 1 can be chosen    let count = findWays(x - 1)Â
    // Count ways in which    // train 2 can be chosen    count += findWays(x - 2)Â
    // Count ways in which    // train 3 can be chosen    count += findWays(x - 3)Â
    // Store the current state    dp[x] = countÂ
    // Return the number of ways    return dp[x]}Â
// Driver Code     // Given Inputlet n = 4Â
// Function call to count// the number of ways to// reach the n-th stationdocument.write(findWays(n))Â
// This code is contributed by shinjanpatraÂ
</script> |
13
Time Complexity: O(N)
Auxiliary Space: O(N)
Efficient approach : Using DP Tabulation method ( Iterative approach )
The approach to solve this problem is same but DP tabulation(bottom-up) method is better then Dp + memorization(top-down) because memorization method needs extra stack space of recursion calls.
Steps to solve this problem :
- Take the integer N as input.
- Initialize a DP table of size N+1 to store the number of ways to reach each station.
- Base cases: set the initial values of the DP table for the first three stations.
- Traverse the stations from 3 to N and for each station:
a. Calculate the number of ways to reach the current station by considering the number of ways to reach the two previous stations.
b. Update the DP table with the new number of ways to reach the current station. - Return the number of ways to reach the N-th station from the DP table.
Implementation :
Â
C++
// C++ program of the above approach#include <bits/stdc++.h>using namespace std;Â
// Function to count the number// of ways to N-th stationint findWays(int x){    // initialize Dp    vector<int> dp(x + 1, 0);Â
    // Base Cases    dp[0] = 1;    dp[1] = 2;    dp[2] = 4;Â
    // initialize count    // Count ways in which    // train 1 can be chosen    int count = dp[2];Â
    for (int i = 3; i <= x; i++) {        // Count ways in which        // train 2 can be chosen        count += dp[i - 2];        // Count ways in which        // train 3 can be chosen        count += dp[i - 3];        // Store the current state        dp[i] = count;    }Â
    // Return the number of ways    return dp[x];}Â
// Driver Codeint main(){Â
    // Given Input    int n = 2;Â
    // Function call to count    // the number of ways to    // reach the n-th station    cout << findWays(n) << "\n";}// this code is contributed by bhardwajji |
Java
// Java program of the above approachimport java.util.*;Â
public class Main{   // Function to count the number// of ways to N-th stationpublic static int findWays(int x) {   // initialize Dpint[] dp = new int[x + 1];      // Base Cases    dp[0] = 1;    dp[1] = 2;    dp[2] = 4;Â
    // initialize count    // Count ways in which    // train 1 can be chosen    int count = dp[2];Â
    for (int i = 3; i <= x; i++)    {               // Count ways in which        // train 2 can be chosen        count += dp[i - 2];               // Count ways in which        // train 3 can be chosen        count += dp[i - 3];               // Store the current state        dp[i] = count;    }Â
    // Return the number of ways    return dp[x];}Â
// Driver Codepublic static void main(String[] args) {       // Given Input    int n = 2;Â
    // Function call to count    // the number of ways to    // reach the n-th station    System.out.println(findWays(n));}} |
Python3
# Function to count the number# of ways to N-th stationdef findWays(x):    # initialize Dp    dp = [0] * (x + 1)Â
    # Base Cases    dp[0] = 1    dp[1] = 2    dp[2] = 4Â
    # initialize count    # Count ways in which    # train 1 can be chosen    count = dp[2]Â
    for i in range(3, x + 1):        # Count ways in which        # train 2 can be chosen        count += dp[i - 2]        # Count ways in which        # train 3 can be chosen        count += dp[i - 3]        # Store the current state        dp[i] = countÂ
    # Return the number of ways    return dp[x]Â
# Driver Codeif __name__ == '__main__':    # Given Input    n = 2Â
    # Function call to count    # the number of ways to    # reach the n-th station    print(findWays(n)) |
C#
using System;Â
class Solution {Â
  // Function to count the number  // of ways to N-th station  public int findWays(int x)  {Â
    // initialize Dp    int[] dp = new int[x + 1];Â
    // Base Cases    dp[0] = 1;    dp[1] = 2;    dp[2] = 4;Â
    // initialize count    // Count ways in which    // train 1 can be chosen    int count = dp[2];Â
    for (int i = 3; i <= x; i++)    {Â
      // Count ways in which      // train 2 can be chosen      count += dp[i - 2];Â
      // Count ways in which      // train 3 can be chosen      count += dp[i - 3];Â
      // Store the current state      dp[i] = count;      count = 0;    }Â
    // Return the number of ways    return dp[x];  }}Â
// Driver Codepublic class Program {Â Â static void Main(string[] args)Â Â {Â Â Â Â Solution obj = new Solution();Â
    // Given Input    int n = 2;Â
    // Function call to count    // the number of ways to    // reach the n-th station    Console.WriteLine(obj.findWays(n));  }}Â
// This code is contributed by usr_dtewbxkn77n |
Javascript
// JavaScript program of the above approachfunction findWays(x) {    // initialize Dp    let dp = new Array(x + 1).fill(0);Â
    // Base Cases    dp[0] = 1;    dp[1] = 2;    dp[2] = 4;Â
    // initialize count    // Count ways in which    // train 1 can be chosen    let count = dp[2];Â
    for (let i = 3; i <= x; i++)     {             // Count ways in which        // train 2 can be chosen        count += dp[i - 2];                 // Count ways in which        // train 3 can be chosen        count += dp[i - 3];                 // Store the current state        dp[i] = count;    }Â
    // Return the number of ways    return dp[x];}Â
// Driver Codelet n = 2;Â
// Function call to count// the number of ways to// reach the n-th stationconsole.log(findWays(n));Â
// This code is contributed by sarojmcy2e |
4
Time Complexity: O(N)
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
