(Leetcode) [Dynamic programming]: Climbing stairs
Topic: Dynamic programming
Difficulty: Easy
Question
Find the number of distinct ways of climbing up the stairs of n steps to the top. We can either climb 1 or 2 steps.
My first solution
- ์ผ๋จ ๋ชจ๋ step์ด ํ ๊ฑธ์์ผ ๋๋ฅผ ๋ฏธ๋ฆฌ ์นด์ดํธ ํ๋ค. int count = 1;
- step=2๊ฐ ํฌํจ๋ ์ ์๋ ์ต๋ ๊ฐ์๋ฅผ ์ฐพ๋๋ค. int max_two = n/2;
- ๋ฃจํ๋ฅผ ์ด์ฉํด์ ๊ฐ๊ธฐ ๋ค๋ฅธ 2์ ๊ฐ์์ 1์ ๊ฐ์๋ก ๋ง๋ค ์ ์๋ ์กฐํฉ์ factorial์ ์ด์ฉํด์ ์ฐพ๋๋ค. ๊ทธ๋ฆฌ๊ณ ์นด์ดํธ์ ๋ํด์ค๋ค.
์ด ์๊ณ ๋ฆฌ์ฆ์ ํจ์จ์ฑ์ด ์์ ๊ฝ์ด๋ค. ๋ ํฉํ ๋ฆฌ์ผ ๊ตฌํ๋ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๊ฐ ์์ ์ค ์์๋๋ฐ C++์๋ ์๋ค๊ณ ํ๋ค. ๊ทธ๋์ ํฉํ ๋ฆฌ์ผ์ ๋ฐ๋ก ๊ตฌํด์ผ ํ๋๋ฐ, ํฉํ ๋ฆฌ์ผ ๊ตฌํ๋ ๊ฒ๋ ๋ฃจํ๊ฐ ์ฌ์ฉ๋๊ธฐ ๋๋ฌธ์ ์ด์ค ๋ฃจํ๊ฐ ๋ง๋ค์ด์ง๊ฒ ๋๋ฏ๋ก time complexity๊ฐ O(n^2)์ด๋ค.
Second solution: use of recursion (without dynamic programming)
geeksforgeeks์์ ์์ด๋์ด ๋์์ ๋ฐ์๋ค.
Reference: https://www.geeksforgeeks.org/count-ways-reach-nth-stair/
The person can reach nth stair from either (n-1)th stair or from (n-2)th stair.
ways(n) = ways(n-1) + ways(n-2)
Third solution: using dynamic programming (efficient approach)
class Solution {
public:
int climbStairs(int n) {
int arr[n+1];
arr[0]=1;
arr[1]=1;
for (int i=2; i<=n; i++) {
arr[i]=0;
arr[i] += arr[i-1];
arr[i] += arr[i-2];
}
return arr[n];
}
};
๋ ๋ฒ์งธ ์๋ฃจ์ ์ recursive function์ dynamic programming ํ์์ผ๋ก ํผ๊ฑฐ๋ค.
Runtime: 0 ms
Memory usage: 6 MB (์์ 40%)
Time complexity: O(n);
Leave a comment