A frog jumps either 1, 2, or 3 steps to go to the top. In how many ways can it reach the top. As the answer will be large find the answer modulo 1000000007.
Time : O(n)
Space : O(n)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution { vector<int> dp; int mod = 1e9 + 7; inthelper(int n){ if(n < 0) return0; if(dp[n] != -1) return dp[n]; dp[n] = (((helper(n - 1) + helper(n - 2)) % mod) + helper(n - 3)) % mod; return dp[n]; } public: //Function to count the number of ways in which frog can reach the top. longlongcountWays(int n){ dp = vector<int>(n + 1, -1); dp[0] = 1; returnhelper(n); } };
Time : O(n)
Space : O(1)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { int mod = 1e9 + 7; public: //Function to count the number of ways in which frog can reach the top. longlongcountWays(int n){ if(n <= 2) return n; int a = 1, b = 1, c = 2; for(int i = 3; i <= n; i++) { int nc = (((a + b) % mod) + c) % mod; a = b; b = c; c = nc; } return c; } };