[Programmers] 2 x n ํƒ€์ผ๋ง

Updated:

2 x n ํƒ€์ผ๋ง

2ย xย nย ํƒ€์ผ๋ง ์„ ํด๋ฆญํ•˜๋ฉด ๋ฐ”๋กœ ์ด๋™ํ•œ๋‹ค.

์„ธ ๋„ค๊ฐ€์ง€ ์˜ˆ์‹œ๋ฅผ ๊ฐ€์ง€๊ณ  ๋ฌธ์ œ ๋‹ต์„ ์ฐพ๋‹ค๋ณด๋ฉด ๊ทœ์น™์ด ๋ณด์ธ๋‹ค.

์ด ๋ฌธ์ œ๋Š” ๋‹คํ–‰ํžˆ ์‰ฌ์›Œ์„œ ๊ทœ์น™์„ ๊ธˆ๋ฐฉ ๋ฐœ๊ฒฌํ•  ์ˆ˜ ์žˆ์ง€๋งŒ ๋ฌดํ„ฑ๋Œ€๊ณ  ํ’€์–ด๋†“๊ณ  ๋ณด๋ฉด ๊ทœ์น™์„ ์ฐพ๊ธฐ ์–ด๋ ค์šธ ์ˆ˜๋„ ์žˆ๋‹ค.

๋•Œ๋ฌธ์— ์ด์ „ ๊ณ„์‚ฐ ๊ฒฐ๊ณผ๋ฅผ ์ด์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ์ž˜ ์ฐพ์•„๋ด์•ผ ํ•œ๋‹ค.

image

๊ฐ€๋กœ ๊ธธ์ด๊ฐ€ N-1 ์ธ๊ฒฝ์šฐ ์„ธ๋กœ๋กœ ํ•œ ์นธ์„ ์ถ”๊ฐ€ํ•˜๋ฉด N ๊ธธ์ด๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค.

๋˜ ๊ฐ€๋กœ ๊ธธ์ด๊ฐ€ N-2 ์ธ ๊ฒฝ์šฐ ๊ฐ€๋กœ ํƒ€์ผ์„ ๋‘ ๊ฐœ ์ถ”๊ฐ€ํ•˜๋ฉด N ๊ธธ์ด๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค.

image

์ด ๊ฒฝ์šฐ๋Š” N-1 ์— ํฌํ•จ๋˜๊ธฐ ๋•Œ๋ฌธ์— ๋”ํ•˜์ง€ ์•Š๋Š”๋‹ค.

๋”ฐ๋ผ์„œ ์ ํ™”์‹์€ dp[i] = dp[i - 1] + dp[i - 2] ๊ฐ€ ๋œ๋‹ค.


def solution(n):
	dp = [0 for _ in range(60001)]
	dp[1] = 1
	dp[2] = 2

	for i in range(3, n + 1):
		dp[i] = (dp[i - 1] + dp[i - 2]) % 1_000_000_007

	return dp[n]



Categories:

Updated:

Leave a comment