70. Climbing Stairs
Climbing Stairs
You are climbing a staircase. It takes n
steps to reach 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: n = 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps
Example 2:
Input: n = 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
Constraints:
1 <= n <= 45
function fib(n) {
if (n <= 1)
return n;
return fib(n-1) + fib(n-2);
}
var climbStairs = function(n) {
if (n < 4) return n;
let a = 1, b = 1, fib;
for(let i = 2; i <= n; i++) {
fib = a + b;
a = b;
b = fib;
}
return fib;
};
var climbStairs = function(n) {
if (n < 4) return n;
let fib = [1, 1];
for (let i = 2; i <= n; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
}
return fib[n];
};
const mul = (
[[a1, a2],[a3, a4]],
[[b1, b2],[b3, b4]]) =>
[[a1 * b1 + a2 * b3, a1 * b2 + a2 * b4],
[a3 * b1 + a4 * b3, a3 * b2 + a4 * b4]];
const matrix = [[0, 1],[1, 1]];
const id = [[1, 0],[0, 1]]
var climbStairs = function(n) {
let result = id;
const bits = (n + 1).toString(2);
for(const bit of bits){
result = mul(result, result);
if(bit === "1"){
result = mul(result, matrix);
}
}
return result[1][0];
}
That’s all folks! In this post, we solved LeetCode problem 70. Climbing Stairs
I hope you have enjoyed this post. Feel free to share your thoughts on this.
You can find the complete source code on my GitHub repository. If you like what you learn. feel free to fork 🔪 and star ⭐ it.
In this blog, I have tried to collect & present the most important points to consider when improving Data structure and logic, feel free to add, edit, comment, or ask. For more information please reach me here
Happy coding!
Comments
Post a Comment