728x90
1932번: 정수 삼각형
첫째 줄에 삼각형의 크기 n(1 ≤ n ≤ 500)이 주어지고, 둘째 줄부터 n+1번째 줄까지 정수 삼각형이 주어진다.
www.acmicpc.net
1. 재귀 ( 시간 초과 )
let cheung = Int(readLine()!)!
var pyramid: [[Int]] = []
var result: Set<Int> = []
for _ in 0 ... cheung - 1 {
pyramid.append(readLine()!.split(separator: " ").map { Int(String($0))! })
}
func SOT(_ floor: Int, _ x: Int, sum: Int) {
if floor == cheung {
result.insert(sum)
return
} else {
SOT(floor + 1, x, sum: sum + pyramid[floor][x])
SOT(floor + 1, x + 1, sum: sum + pyramid[floor][x])
}
}
SOT(0, 0, sum: 0)
print(Int(result.max()!))
2. 메모이제이션 ( AC )
let cheung = Int(readLine()!)!
var pyramid: [[Int]] = []
for _ in 0 ... cheung - 1 {
pyramid.append(readLine()!.split(separator: " ").map { Int(String($0))! })
}
if cheung == 1 {
print(pyramid[0][0])
} else {
for i in 1 ... pyramid.count - 1 {
for j in 0 ... pyramid[i].count - 1 {
if j == 0 {
pyramid[i][j] += pyramid[i-1][j]
} else if j == pyramid[i].count - 1 {
pyramid[i][j] += pyramid[i-1][j-1]
} else {
pyramid[i][j] += [pyramid[i-1][j], pyramid[i-1][j-1]].max()!
}
}
}
print(pyramid[pyramid.count-1].max()!)
}
728x90
'PS (Problem Solving)' 카테고리의 다른 글
[BOJ, Python] 10026 - 적록색약 ( with DFS ) (0) | 2022.09.08 |
---|---|
[BOJ, Swift] 1021 - 회전하는 큐 ( with 덱(Dequeue) ) (0) | 2022.08.13 |
[BOJ, Python] 람다(lambda)를 활용한 리스트 정렬 (0) | 2022.07.24 |
[BOJ, Swift] 18258 - 큐 2 (0) | 2022.07.22 |
[BOJ, Python] 입출력 정리 (0) | 2022.06.22 |