๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm/Programmers

[Programmers] ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜

 

 

๋ฌธ์ œ 

 

ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜๋Š” 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 ์ดํ•˜์ธ ์ž์—ฐ์ˆ˜์ž…๋‹ˆ๋‹ค.

 

 

ํ•ด์„ค ์ฝ”๋“œ 
def solution(n):
    answer = []
    for i in range(n+1):
        if i == 0 or i == 1:
            answer.append(i)
        else:
            f = answer[i-2] + answer[i-1]
            answer.append(f%1234567)
    return answer[-1]
๋ถ„์„ > ์ด ๋ฌธ์ œ๋ฅผ ํ†ตํ•ด ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜์— ๋Œ€ํ•œ ๊ฐœ๋…์„ ์žก์„ ์ˆ˜ ์žˆ์—ˆ๋‹ค. ์šฐ์„  0๋ฒˆ์งธ์™€ 1๋ฒˆ์งธ๋Š” ๊ทœ์น™์— ์ƒ๊ด€์—†์ด i ๊ฐ’์ด ๊ทธ๋Œ€๋กœ input ๋˜๋ฏ€๋กœ ๋”ฐ๋กœ ์กฐ๊ฑด์„ ๋นผ์„œ ์ ์–ด์ฃผ๊ณ  3๋ฒˆ์งธ ์ˆ˜๋ถ€ํ„ฐ๋Š” ๊ทœ์น™์— ๋”ฐ๋ผ ๊ทธ ๋‹ค์Œ ์ˆ˜๊ฐ€ append ๋˜๊ธฐ ๋•Œ๋ฌธ์— ๊ทœ์น™์„ ์ ์–ด์„œ ๋ฐ˜๋ณต๋ฌธ์„ ๋Œ๋ ค์ฃผ๋ฉด ๋œ๋‹ค. 

 

 

 

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜

ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜๋Š” 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) =

programmers.co.kr