๐Ÿ€TIL๐Ÿ€[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] Coding Test ์Šคํ„ฐ๋””15

PYMยท2023๋…„ 9์›” 6์ผ
0

๐Ÿ€TIL๐Ÿ€Coding Test

๋ชฉ๋ก ๋ณด๊ธฐ
13/16
post-thumbnail

์ธ๋„ค์ผ์€ ์กธ์—… ์„ ๋ฌผ๋กœ ๋ฐ›์€ ๋ชฉ๊ฑธ์ด๐Ÿ€ ๋“œ๋””์–ด ์กธ์—…ํ–ˆ๋‹ค~

Q1. ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜์—ด

ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜๋Š” F(0) = 0, F(1) = 1์ผ ๋•Œ, 1 ์ด์ƒ์˜ n์— ๋Œ€ํ•˜์—ฌ F(n) = F(n-1) + F(n-2) ๊ฐ€ ์ ์šฉ๋˜๋Š” ์ˆ˜ ์ž…๋‹ˆ๋‹ค.

์˜ˆ๋ฅผ๋“ค์–ด

F(2) = F(0) + F(1) = 0 + 1 = 1
F(3) = F(1) + F(2) = 1 + 1 = 2
F(4) = F(2) + F(3) = 1 + 2 = 3
F(5) = F(3) + F(4) = 2 + 3 = 5
์™€ ๊ฐ™์ด ์ด์–ด์ง‘๋‹ˆ๋‹ค.

2 ์ด์ƒ์˜ n์ด ์ž…๋ ฅ๋˜์—ˆ์„ ๋•Œ, n๋ฒˆ์งธ ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜๋ฅผ 1234567์œผ๋กœ ๋‚˜๋ˆˆ ๋‚˜๋จธ์ง€๋ฅผ ๋ฆฌํ„ดํ•˜๋Š” ํ•จ์ˆ˜, solution์„ ์™„์„ฑํ•ด ์ฃผ์„ธ์š”.

์ œํ•œ ์‚ฌํ•ญ

  • n์€ 2 ์ด์ƒ 100,000 ์ดํ•˜์ธ ์ž์—ฐ์ˆ˜์ž…๋‹ˆ๋‹ค.

๐Ÿฃ๋‚ด ์ฝ”๋“œ

function solution(n) {
    /*
    //์žฌ๊ท€ ํ•จ์ˆ˜ ์‚ฌ์šฉ (์‹œ๊ฐ„ ์ดˆ๊ณผ)
    const recurse = (num) => {
        if(num === 0){
            return 0
        }
        if(num === 1){
            return 1
        }
        return recurse(num-1) + recurse(num-2)
    }
    
    return recurse(n)
    */ 
    
    // DP ์‚ฌ์šฉ ํ’€์ด 
    
    let first = 0, second = 1, target = 0;
    
    for(let i = 2; i <= n; i++){
        target = (first + second) % 1234567;
        
        first = second; 
        second = target;
    }
    
    return target; 
    
}
  • ์ฒ˜์Œ์—๋Š” ์‹œ๊ฐ„ ๋ณต์žก๋„๋ฅผ ์ƒ๊ฐ ๋ชปํ•˜๊ณ  ์žฌ๊ท€๋กœ ํ’€์–ด๋ดค๋Š”๋ฐ, ์‹œ๊ฐ„ ์ดˆ๊ณผ๊ฐ€ ๋–ด๋‹ค...! ๊ทธ๋ž˜์„œ DP๋กœ ๋‹ค์‹œ ํ’€์—ˆ๋‹ค.

  • for๋ฌธ์„ 2๋ถ€ํ„ฐ n๊นŒ์ง€ ๋ˆ๋‹ค.

    • 0๊ณผ 1์„ ์•ˆ๋„๋Š” ์ด์œ : i=2์ผ๋•Œ target = (first + second) ์—์„œ ์ด๋ฏธ F(2) = F(0) + F(1)์ด ๋˜๊ธฐ ๋•Œ๋ฌธ์—!
  • target์€ F(n)
    first๋Š” F(n-1)
    second๋Š” F(n-2)๋ผ๊ณ  ์ƒ๊ฐํ•˜๋ฉด ๋œ๋‹ค.

  • first = second์™€ second = target ์œผ๋กœ n๋ฅผ ํ•˜๋‚˜์”ฉ ์˜ฌ๋ ค ์ค€๋‹ค.

๐Ÿฆ–๋Š๋‚€ ์ 

DP๋กœ ํ‘ธ๋‹ˆ๊นŒ ๋กœ์ง์€ ์žฌ๊ท€๋ž‘ ๋น„์Šทํ•œ๋ฐ ์‹œ๊ฐ„ ๋ณต์žก๋„๊ฐ€ ๋” ์ค„์–ด๋“ค์–ด์„œ ์‹ ๊ธฐํ–ˆ๋‹ค. ๋‹ค์Œ๋ถ€ํ„ฐ๋Š” ๋ฌธ์ œ ํ’€๊ธฐ ์ „์— ์‹œ๊ฐ„ ๋ณต์žก๋„๋ฅผ ์ข€ ๋” ๊ผผ๊ผผํžˆ ์ƒ๊ฐํ•˜๊ณ  ํ’€์ž!

profile
๋ชฉํ‘œ๋Š” "ํ•จ๊ป˜ ์ผํ•˜๊ณ  ์‹ถ์€, ํ•จ๊ป˜ ์ผํ•ด์„œ ์ข‹์€" Front-end ๊ฐœ๋ฐœ์ž

0๊ฐœ์˜ ๋Œ“๊ธ€