๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
TIL๐Ÿ”ฅ/์ฝ”๋”ฉํ…Œ์ŠคํŠธ

[ํ•ญํ•ด99ํด๋Ÿฝ] Java ๋น„๊ธฐ๋„ˆ_Day 6 Climbing Stairs

by hk713 2025. 4. 7.

์˜ค๋Š˜์˜ ๋ฌธ์ œ >> https://leetcode.com/problems/climbing-stairs/

 

[ ์ƒ๊ฐ ํ๋ฆ„ ] 

๊ณ„๋‹จ์˜ค๋ฅด๊ธฐ ๋ฌธ์ œ๋Š” ์œ ๋ช…ํ•œ ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜์—ด ๋ฌธ์ œ๋‹ค.

n๋ฒˆ์งธ ๊ณ„๋‹จ์— ์˜ค๋ฅด๋Š” ๋ฐฉ๋ฒ•์€ n-1๋ฒˆ์งธ ๊ณ„๋‹จ์—์„œ 1์นธ ์˜ค๋ฅด๊ฑฐ๋‚˜ n-2๋ฒˆ์งธ ๊ณ„๋‹จ์—์„œ 2์นธ ์˜ค๋ฅด๋Š” ๋ฐฉ๋ฒ•๋ฐ–์— ์—†๋‹ค.

๋”ฐ๋ผ์„œ f(n) = f(n-1)+f(n-2) ๋กœ ํ‘œํ˜„ํ•  ์ˆ˜ ์žˆ๋Š” ๊ฒƒ์ด๋‹ค.

 

[ Java ]

class Solution {
    public int climbStairs(int n) {
        if (n<=2) return n;
        int[] answer = new int[n+1];
        answer[1] = 1;
        answer[2] = 2;

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

        return answer[n];
    }
}

๋Œ“๊ธ€