1. λ¬Έμ
2. μ μΆλ ₯
3. μ μΆλ ₯ μμ
4. λ¬Έμ μ€κ³
- μ λ¬Έμ μ κ²½μ° μ λͺ ν νΈμ§κ±°λ¦¬ μκ³ λ¦¬μ¦κ³Ό μ μ¬νλ°, λ€λ₯Έ μ μ μ½μ , μμ , κ΅μ²΄ μ°μ°μ€ μ½μ , μμ λ κ°μ§ μ°μ°λ§ μ‘΄μ¬νλ€λ μ
- λ°λΌμ A λ¬Έμμ΄μ μνλ²³λ€μ νμΌλ‘, B λ¬Έμμ΄μ μνλ²³λ€μ μ΄λ‘ λ°°μΉνμ λ, λ°μν μ μλ μ°μ°μ λν΄ μ μ₯ν΄ λκ°λ λμ κ³νλ² μκ³ λ¦¬μ¦μ μ¬μ©ν μ μμ
- λ¨Όμ , A[i] == B[j] λΌλ©΄, λ μ΄μ μνν΄μΌν μ°μ°μ΄ μμΌλ―λ‘, μΌμͺ½ λκ°μ μμμ κ°μ κ·Έλλ‘ λ³΅μ¬νλ©΄ λκ³ ,
- A[i]μ B[j]κ° κ°μ§ μλ€λ©΄, table[i][j]μ μμ κ° + 1μΈ μμ μ°μ°ν κ°κ³Ό, μΌμͺ½ κ° + 1μΈ μ½μ μ°μ°ν κ° μ€ μμ κ°μ νμ¬ table[i][j]μ μ μ₯νλ©΄ λ¨
- λ°λΌμ, table[i][j] = A[0 ~ i]μμ B[0 ~ j]λ₯Ό λ§λ€κΈ° μν΄ μ½μ /νΉμ μμ μ°μ°μ λν μ΅μκ°μ΄λ©°,
- table[i][j] = A[i] == B[j], table[i - 1][j - 1]μ΄κ³ , μλλΌλ©΄, min(table[i - 1][j], table[i][j - 1]) + 1μ μ νμμ ꡬν μ μκ³ ,
- λ¬Έμ μ ν¬κΈ° 1000μ nμ΄λΌκ³ νμ λ, O(n^2)μ μκ°λ³΅μ‘λλ‘ λ¬Έμ λ₯Ό ν΄κ²°ν μ μμ
5. μ 체 μ½λ
//MARK: - λ λ¬Έμμ΄ μ¬μ΄μ 거리
//MARK: - Framework
import Foundation
//MARK: - Variable
var table: [[Int]] = []
//MARK: - Function
func solution() -> Void {
//MARK: - Input
guard let A: String = readLine() else { return }
guard let B: String = readLine() else { return }
table = Array(repeating: Array(repeating: 0, count: B.count), count: A.count)
//MARK: - Process
for i in 0..<A.count {
table[i][0] = i
}
for i in 0..<B.count {
table[0][i] = i
}
for i in 1..<A.count {
for j in 1..<B.count {
if A[A.index(A.startIndex, offsetBy: i)] == B[B.index(B.startIndex, offsetBy: j)] {
table[i][j] = table[i - 1][j - 1]
} else {
table[i][j] = table[i - 1][j] < table[i][j - 1] ? table[i - 1][j] + 1 : table[i][j - 1] + 1
}
}
}
//MARK: - Output
print(table[A.count - 1][B.count - 1])
}
solution()
μ 체μ½λλ μ¬κΈ°μμ νμΈν μ μμ΅λλ€.
'Swift Data Structure And Algorithm > Dynamic Programming' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
ν°λ¦°λ둬 λ§λ€κΈ° (0) | 2022.04.12 |
---|---|
μ°μ λΆλΆ μ΅λν© L (0) | 2022.04.12 |
μμ μ±μ·¨ (0) | 2022.04.12 |
μ κ³±μμ ν© (0) | 2022.04.08 |
μ§μ¬κ°νλ°°μΉμκ²½μ°μμ (0) | 2022.04.08 |