# 풀이 중
import Foundation
let n = Int(readLine()!)!
var numbers:[Int] = []
let input = readLine()!.map { $0 }
input.forEach {
if let number = Int(String($0)) {
numbers.append(number)
}
}
print(numbers)
func combination<T>(_ elements: [T], _ k: Int) -> [[T]] {
var results: [[T]] = []
var visited: [Bool] = .init(repeating: false, count: elements.count)
func combi(_ now: [T], _ index: Int) {
if now.count == k {
results.append(now)
return
}
for i in index..<elements.count {
if visited[i] { continue }
combi(now + [elements[i]], i + 1)
}
}
combi([], 0)
return results
}
func calculate(_ start: Int, _ end: Int) -> Int {
if start == end {
return numbers[start]
} else if (end - start == 2) {
return calc(Int(String(input[start]))!, String(input[start + 1]), Int(String(input[end]))!)
}
var slice = numbers[start..<end+1].map { Int($0) }
var combinations = combination(slice, 2)
return 0
}
func calc(_ lhs: Int, _ symbol: String, _ rhs: Int) -> Int {
switch symbol {
case "+":
return lhs + rhs
case "-":
return lhs - rhs
case "*":
return lhs * rhs
default:
return 0
}
}
# 풀이
- 누적합 완전탐색 문제
- 주요 로직: 앞에 세개씩 재귀적으로 선택하는 방식
- a,b,c 세개의 숫자가 있을때 (a,b) & c 로 계산할지 a & (b,c)로 계산할지를 선택한뒤 다음 인덱스로 넘어가는 방식
import Foundation
let n = Int(readLine()!)!
var numbers:[Int] = []
var operators: [String] = []
var ret = Int.min
let input = readLine()!.map { $0 }
input.forEach {
if let number = Int(String($0)) {
numbers.append(number)
} else {
operators.append(String($0))
}
}
func oper(_ lhs: Int, _ symbol: String, _ rhs: Int) -> Int {
switch symbol {
case "+":
return lhs + rhs
case "-":
return lhs - rhs
case "*":
return lhs * rhs
default:
return 0
}
}
func go(_ here: Int, _ reducer: Int) {
if here == numbers.count - 1 {
ret = max(ret, reducer)
return
}
go(here + 1, oper(reducer, operators[here], numbers[here + 1]))
if here + 2 <= numbers.count - 1 {
let temp = oper(numbers[here + 1], operators[here + 1], numbers[here + 2])
go(here + 2, oper(reducer, operators[here], temp))
}
}
go(0, numbers[0])
print(ret)