[BOJ, Swift] 1932 - 정수 삼각형

2022. 5. 8. 14:27·PS (Problem Solving)
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
'PS (Problem Solving)' 카테고리의 다른 글
  • [BOJ, Swift] 1021 - 회전하는 큐 ( with 덱(Dequeue) )
  • [BOJ, Python] 람다(lambda)를 활용한 리스트 정렬
  • [BOJ, Swift] 18258 - 큐 2
  • [BOJ, Python] 입출력 정리
100두산
100두산
출발하게 만드는 힘이 동기라면, 계속 나아가게 만드는 힘은 습관이다.
  • 100두산
    정상에서 보자 ✈️
    100두산
  • 전체
    오늘
    어제
    • 분류 전체보기 (126)
      • Life (6)
        • living (1)
      • Research (6)
      • AI (20)
      • Dev (45)
        • iOS (28)
        • Web (4)
        • flutter (9)
        • etc (4)
      • PS (Problem Solving) (23)
      • Computer Science and Engine.. (21)
        • Data Structures and Algorit.. (13)
        • OOP (Object Oriented Progra.. (8)
      • etc (5)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
    • 글쓰기
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    D3
    백트래킹
    c++
    티스토리챌린지
    SKT
    파이썬
    BOJ
    SKTelecom
    xcode
    AI
    PS
    알고리즘
    swift
    Python
    Challenger
    백준
    자료구조
    오블완
    ios
    TIP
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.2
100두산
[BOJ, Swift] 1932 - 정수 삼각형
상단으로

티스토리툴바