(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

  1. ์ผ๋‹จ ๋ชจ๋“  step์ด ํ•œ ๊ฑธ์Œ์ผ ๋•Œ๋ฅผ ๋ฏธ๋ฆฌ ์นด์šดํŠธ ํ•œ๋‹ค. int count = 1;
  2. step=2๊ฐ€ ํฌํ•จ๋  ์ˆ˜ ์žˆ๋Š” ์ตœ๋Œ€ ๊ฐœ์ˆ˜๋ฅผ ์ฐพ๋Š”๋‹ค. int max_two = n/2;
  3. ๋ฃจํ”„๋ฅผ ์ด์šฉํ•ด์„œ ๊ฐ๊ธฐ ๋‹ค๋ฅธ 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);

Categories:

Updated:

Leave a comment