[Algorithm] NμΌλ‘ νν (κΉμ΄ μ°μ νμ(DFS))
π₯ λ¬Έμ
μλμ κ°μ΄ 5μ μ¬μΉμ°μ°λ§μΌλ‘ 12λ₯Ό ννν μ μμ΅λλ€.
12 = 5 + 5 + (5 / 5) + (5 / 5)
12 = 55 / 5 + 5 / 5
12 = (55 + 5) / 5
5λ₯Ό μ¬μ©ν νμλ κ°κ° 6,5,4μ
λλ€. κ·Έλ¦¬κ³ μ΄μ€ κ°μ₯ μμ κ²½μ°λ 4μ
λλ€.
μ΄μ²λΌ μ«μ Nκ³Ό numberκ° μ£Όμ΄μ§ λ, Nκ³Ό μ¬μΉμ°μ°λ§ μ¬μ©ν΄μ ννν μ μλ λ°©λ² μ€ N μ¬μ© νμμ μ΅μκ°μ return νλλ‘ solution ν¨μλ₯Ό μμ±νμΈμ.
π€ νμ΄ λ°©λ²
μ΄ λ¬Έμ λ λμ κ³νλ²(Dynamic Programming)μΌλ‘ λΆλ₯λμ΄ μμ§λ§, κΉμ΄ μ°μ νμ(Depth-First Search)μΌλ‘ νμλ€.
κΉμ΄ μ°μ νμμ΄λ 루νΈλ
Έλμμ λΆν° μμν΄μ λ€μ λΈλμΉλ‘ λμ΄κ°κΈ° μ μ ν΄λΉ λΈλμΉλ₯Ό μλ²½νκ² νμνλ λ°©λ²μ΄λ€.
- λ³μ
countN
: Nμ΄ μ¬μ©λ κ°μresultN
: Nμ μ΄μ©νμ¬ κ³μ°ν μμ κ²°κ³ΌcalN
: n ~ nnnnnnnnμ μ
if countN > 8 { return }
- Nμ 1μ΄μ 9 μ΄νμ΄λ€. 8μ μ΄κ³Όνλ©΄(0 ~ 8κΉμ§ μ΄ 9κ°λ₯Ό μ΄κ³Όνλ©΄) 리ν΄ν΄μ€λ€. μ΄λ κ²°κ³Όλ -1μ΄ λλ€.
if bumber == resultN
:number
μ κ³μ°ν μμ κ²°κ³ΌresultN
μ΄ κ°μ κ²½μ°result == -1
: μμ§ κ³μ°λ κ²°κ³Όκ° μμ΄ μ²μμΌλ‘result
λ₯Ό μ λ°μ΄νΈ ν΄μ€μΌ νλ κ²½μ°countN < result
: νμ¬result
μ κ° λ³΄λ€ λ μ μ κ°μμ Nμ μ¬μ©ν κ²½μ°- μ λκ°μ κ²½μ°μ
result
λ₯Ό Nμ΄ μ¬μ©λ κ°μcountN
μΌλ‘ μ λ°μ΄νΈ ν΄μ£Όκ³ 리ν΄νλ€.
calN
μ n ~ nnnnnnnnμ μλ₯Ό νλμ© λ£μ΄μ£Όλ©° νμνλ€.for i in 0..<8 { calN = calN * 10 + N ... }
dfs(N, number, countN + 1 + i, resultN + calN, &result)
:resultN
μ λνμ¬calN
μ +, -, *, / μ°μ°μ μννλ€.countN + 1 + i
:countN
μ Nμ΄ μ¬μ©λ κ°μλ₯Ό λ겨μ€λ€.resultN + calN
:resultN
μ κ³μ°ν μμ κ²°κ³Όλ₯Ό λ겨μ€λ€.
π©π»π» Swift Code
import Foundation
func solution(_ N:Int, _ number:Int) -> Int {
var result: Int = -1
dfs(N, number, 0, 0, &result)
return result
}
func dfs(_ N:Int, _ number:Int, _ countN:Int, _ resultN:Int, _ result: inout Int) {
var calN = 0
if countN > 8 {
return
}
if number == resultN && (result == -1 || countN < result) {
result = countN
return
}
for i in 0..<8 {
calN = calN * 10 + N
dfs(N, number, countN + 1 + i, resultN + calN, &result)
dfs(N, number, countN + 1 + i, resultN - calN, &result)
dfs(N, number, countN + 1 + i, resultN * calN, &result)
dfs(N, number, countN + 1 + i, resultN / calN, &result)
}
}
μ½λ©ν μ€νΈ μ°μ΅ - NμΌλ‘ νν
programmers.co.kr