A group of hikers need to make it to the top of a mountain. They can only move forward…
- User
A group of hikers need to make it to the top of a mountain. They can only move forward by either hopping over one rock or two rocks at a time. How many different ways can they reach the summit of the mountain, given that there are n rocks to hop over? Example 1: Input: n = 2 Output: 2 Explanation: There are two ways to reach the summit of the mountain. 0. Hopping over one rock, then one more rock 0. Hopping over two rocks at once Example 2: Input: n = 3 Output: 3 Explanation: There are three ways to reach the summit of the mountain. please do it in javascript
- Assistant
To solve this problem, we can use a dynamic programming approach. The idea is quite simple and relates to the fact that to reach the
n-th rock, a hiker could have either come from the(n-1)-th rock by taking a single hop or from the(n-2)-th rock by taking a double hop. The base cases are whenn = 1, there's obviously only one way to reach the summit (a single hop), and whenn = 2, as you've described, there are two possible ways (two single hops or one double hop).The code to achieve this would be as below:
function countWays(n) { // Base cases if (n === 1) return 1; if (n === 2) return 2; // dp[i] will store the number of ways to reach the i-th rock let dp = new Array(n + 1); dp[1] = 1; // Only one way to reach the 1st rock dp[2] = 2; // Two ways to reach the 2nd rock: (1+1) or (2) // Calculate the number of ways for all other rocks for (let i = 3; i <= n; i++) { dp[i] = dp[i - 1] + dp[i - 2]; } return dp[n]; } // Example usage: console.log(countWays(2)); // Outputs: 2 console.log(countWays(3)); // Outputs: 3