Count number of ways to cover a distance | Set 2 | Function to return the count of the total number of ways to cover the distance with 1 , 2 and 3 steps ; Base conditions ; To store the last three stages ; Find the numbers of steps required to reach the distance i ; Return the required answer ; Driver code
function countWays ( n ) { if ( n == 0 ) return 1 ; if ( n <= 2 ) return n ; let f0 = 1 , f1 = 1 , f2 = 2 ; let ans = 0 ; for ( let i = 3 ; i <= n ; i ++ ) { ans = f0 + f1 + f2 ; f0 = f1 ; f1 = f2 ; f2 = ans ; } return ans ; } let n = 4 ; document . write ( countWays ( n ) ) ;