
LeetCode 70-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:
Example 2:
class Solution {
public int climbStairs(int n) {
if (n <= 2) {
return n;
}
int first = 1;
int second = 2;
for (int i = 3; i <= n; i++) {
int thrid = first + second;
first = second;
second = thrid;
}
return second;
}
}
first는 1칸일 때의 방법 수, second은 2칸일 때의 방법 수를 의미한다.thrid에 현재 계단의 경우의 수를 저장하고, first, second를 다음 계산을 위해 한 칸씩 앞으로 옮긴다.second에는 n칸 계단을 올라가는 총 방법 수가 들어 있다.피보나치 수열에 관련된 문제들을 몇 개 풀어서 응용해봐야겠다는 생각이 든다.