February 29, 2024

Viiisit [LeetCode] - 70. Climbing Stairs

#php#javascript#ruby

keep learning, keep coding!

Problem - 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?

翻譯蒟蒻

一次只能爬一階或兩階,求出最多有幾種可以爬到最高的方法



Solution - JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* @param {number} n
* @return {number}
*/
var climbStairs = function(n) {
let arr = [0, 1, 2];
if (n < 3) {
return arr[n];
}

for (let i = 3; i <= n; i++) {
arr[i] = arr[i - 1] + arr[i - 2];
}

return arr[n];
};

Solution - Ruby

1
2
3
4
5
6
7
8
9
10
11
def climb_stairs(n)
arr = [0, 1, 2]

return arr[n] if n < 3

(3..n).each do |i|
arr[i] = arr[i-1] + arr[i-2]
end

return arr[n]
end

Solution - PHP

1
2
3
4
5
6
7
8
9
10
11
12
13
function climbStairs($n) {
$arr = [0, 1, 2];

if ($n < 3) {
return $arr[$n];
};

for ($i = 3; $i <= $n; $i++) {
$arr[$i] = $arr[$i-1] + $arr[$i-2];
};

return $arr[$n];
}

LeetCode 傳送門 - Climbing Stairs