๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
3๏ธโƒฃ Swift/Problem Solving

[Swift Algorithm] 1, 2, 3 ๋”ํ•˜๊ธฐ BOJ #9095

by seolhee2750 2021. 10. 19.
๋ฌธ์ œ ์„ค๋ช…

์ •์ˆ˜ 4๋ฅผ 1, 2, 3์˜ ํ•ฉ์œผ๋กœ ๋‚˜ํƒ€๋‚ด๋Š” ๋ฐฉ๋ฒ•์€ ์ด 7๊ฐ€์ง€๊ฐ€ ์žˆ๋‹ค. ํ•ฉ์„ ๋‚˜ํƒ€๋‚ผ ๋•Œ๋Š” ์ˆ˜๋ฅผ 1๊ฐœ ์ด์ƒ ์‚ฌ์šฉํ•ด์•ผ ํ•œ๋‹ค.

  • 1+1+1+1
  • 1+1+2
  • 1+2+1
  • 2+1+1
  • 2+2
  • 1+3
  • 3+1

์ •์ˆ˜ n์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, n์„ 1, 2, 3์˜ ํ•ฉ์œผ๋กœ ๋‚˜ํƒ€๋‚ด๋Š” ๋ฐฉ๋ฒ•์˜ ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

 

์ž…๋ ฅ

์ฒซ์งธ ์ค„์— ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค์˜ ๊ฐœ์ˆ˜ T๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๊ฐ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋Š” ํ•œ ์ค„๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ๊ณ , ์ •์ˆ˜ n์ด ์ฃผ์–ด์ง„๋‹ค. n์€ ์–‘์ˆ˜์ด๋ฉฐ 11๋ณด๋‹ค ์ž‘๋‹ค.

 

์ถœ๋ ฅ

๊ฐ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋งˆ๋‹ค, n์„ 1, 2, 3์˜ ํ•ฉ์œผ๋กœ ๋‚˜ํƒ€๋‚ด๋Š” ๋ฐฉ๋ฒ•์˜ ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

 

์ž…์ถœ๋ ฅ ์˜ˆ์ œ

์ž…๋ ฅ

3
4
7
10

์ถœ๋ ฅ

7
44
274

 

๋‚ด ๋ฌธ์ œ ํ’€์ด
let cases = Int(readLine()!)!

func solution(_ n: Int) -> Int {
    if n == 1 { return 1 }
    if n == 2 { return 2 }
    if n == 3 { return 4 }
    else { return solution(n-3) + solution(n-2) + solution(n-1) }
}

for _ in 0..<cases { print(solution(Int(readLine()!)!)) }

๐Ÿ‘‰ DP ๋ฌธ์ œ๋กœ, ์ ํ™”์‹์„ ํ™œ์šฉํ•˜์—ฌ ์žฌ๊ท€ํ•จ์ˆ˜๋กœ ํ’€์ดํ•˜๋Š”๊ฒƒ์ด ํฌ์ธํŠธ!


[์ ํ™”์‹]

  • 1์€ 1 = 1๊ฐœ
  • 2๋Š” 1+1 = 1๊ฐœ
  • 3์€ 1+1+1, 1+2, 2+1 = 3๊ฐœ
  • 4๋Š” 1+1+1+1, 1+1+2, 1+2+1, 2+1+1, 2+2, 1+3, 3+1, 4 = 7๊ฐœ
  • 5๋Š” 1+1+1+1, (1+1+1+2 X 4), (1+2+2 X 3), (1+1+3 X 3), (2+3 X 2), 5 = 13๊ฐœ

=> ์ด๋ ‡๊ฒŒ ๋‚ด๊ฐ€ ๊ตฌํ•˜๊ณ ์ž ํ•˜๋Š” ์ˆ˜์˜ ์กฐํ•ฉ ๊ฐœ์ˆ˜๋Š” ์ด์ „ 3๊ฐœ ์ˆ˜๋“ค์˜ ์กฐํ•ฉ ๊ฐœ์ˆ˜ ํ•ฉ๊ณผ ๊ฐ™์Œ

=> solution(n) = solution(n-3) + solution(n-2) + solution(n-1) ์œผ๋กœ ์ ํ™”์‹ ๊ตฌํ˜„ ๊ฐ€๋Šฅ!

 

[๋ฌธ์ œ ํ’€์ด]

  • n์ด 1, 2, 3์ผ ๊ฒฝ์šฐ๋Š” ์ด์ „ ์„ธ ๊ฐœ ์ˆ˜ ์กฐํ•ฉ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•ด์ค„ ์ˆ˜ ์—†์œผ๋ฏ€๋กœ ์˜ˆ์™ธ๋กœ ์ฒ˜๋ฆฌํ–ˆ๋‹ค.
  • ๊ทธ ์™ธ์˜ ๊ฒฝ์šฐ์—๋Š” ๋ชจ๋‘ ์œ„์—์„œ ๊ตฌํ•œ ์ ํ™”์‹์„ ์žฌ๊ท€ ํ˜ธ์ถœ๋กœ ๊ตฌํ˜„ํ–ˆ๋‹ค.

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • DP๋Š” ๋ฉ”๋ชจ์ด์ œ์ด์…˜๊ณผ ์ ํ™”์‹์„ ์‚ฌ์šฉํ•ด์„œ ๋ฌธ์ œ๋ฅผ ํ’€์ดํ•˜๋Š” ๊ฒƒ ๊ฐ™๋‹ค.
    ์—ฌ๊ธฐ์„œ๋Š” ์ ํ™”์‹์„ ๊ตฌํ•ด์ฃผ๋Š”๊ฒŒ ๊ด€๊ฑด์ด์—ˆ๋Š”๋ฐ, ๋‹คํ–‰ํžˆ ์–ด๋ ค์šด ํŒจํ„ด์€ ์•„๋‹ˆ์—ˆ๋‹ค.
    ํ•˜์ง€๋งŒ ์•ž์œผ๋กœ ๋” ์–ด๋ ค์šด,,! ์ ํ™”์‹๋“ค์„ ์ƒ๊ฐํ•ด๋‚ผ ์ˆ˜ ์žˆ์„์ง€ ๊ฑฑ์ •์ด ๋˜๊ธด ํ•œ๋‹ค.
    ์ ํ™”์‹๋“ค๋„ ํŠน์ •ํ•œ ํŒจํ„ด์ด๋‚˜ ์œ ํ˜•์ด ์žˆ๋Š”์ง€ ๋งŽ์ด ํ’€์–ด๋ด์•ผ ์•Œ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™๋‹ค.

 


๋ฌธ์ œ

https://www.acmicpc.net/problem/9095

๋Œ“๊ธ€