Climbing Stairs

ํ‹€๋ฆฐ ์ด์œ  1. base case(boundary case) ๋ฅผ ์ž˜๋ชป ์„ธ์› ๋‹ค. - dp[1] = 1, dp[2] = 2 (X) dp[0] = 1, dp[1] = 1(O) 2. ์ ํ™”์‹์„ ์ž˜๋ชป ์„ธ์› ๋‹ค. - dp[n] = dp[n-1] * 2 - 1 (X) dp[n] = dp[n-1] + dp[n-2] (O)

์ž๋ฃŒ ๊ตฌ์กฐ(Data Structure) Memoization์„ ์œ„ํ•œ 1์ฐจ์› ๋ฐฐ์—ด

์•Œ๊ณ ๋ฆฌ์ฆ˜ 1. base๊ฐ€ ๋˜๋Š” sub-problem์˜ ํ•ด๋ฅผ ๊ตฌํ•œ๋‹ค. - dp[0], dp[1] 2. 1์˜ sub-problem์˜ ํ•ด๋ฅผ ํ†ตํ•ด ์ตœ์ข… ํ•ด๋ฅผ ๊ตฌํ•œ๋‹ค. ๋ฌธ์ œ์—์„œ ์ฃผ์–ด์ง„ ๊ฒƒ์ฒ˜๋Ÿผ, ํ•œ๋ฒˆ์— 1 ๋˜๋Š” 2 step์”ฉ ์˜ฌ๋ผ๊ฐˆ ์ˆ˜ ์žˆ๋‹ค. n๊ฐœ์˜ ๊ณ„๋‹จ์ธ ๊ฒฝ์šฐ, 1๊ฐœ์˜ ๊ณ„๋‹จ์„ ์˜ฌ๋ผ๊ฐ€๋Š” ๊ฒฝ์šฐ ๋˜๋Š” 2๊ฐœ์˜ ๊ณ„๋‹จ์„ ์˜ฌ๋ผ๊ฐ€๋Š” ๊ฒฝ์šฐ = stairs(n) = stairs(n-1) + stairs(n-2)

์•Œ๊ณ ๋ฆฌ์ฆ˜์„ Java๋กœ ๊ตฌํ˜„

class Solution {
    public int climbStairs(int n) {
        int dp[] = new int[n+1];
        dp[0] = 1;
        dp[1] = 1;
        
        for(int i=2;i<=n;i++) {
            dp[i] = dp[i-1] + dp[i-2];
        }
        return dp[n];
    }
}

Last updated