티스토리 뷰

 

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()!)
}
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함