// 주사위를 뽑는 경우의 수funcselectDicesCombination() -> [[Bool]] {
var ret = [[Bool]]()
var visit =Array(repeating: false, count: n)
funcdfs(_i: Int, _c: Int) {
if c == n /2 { ret.append(visit); return }
for i in i..<n {
visit[i] =true
dfs(i+1, c+1)
visit[i] =false
}
}
dfs(1, 0)
return ret
}
// 주사위를 굴리는 모든 경우의 수funcRollingDiceCombination() -> [[Int]] {
var ret = [[Int]]()
funcdfs(_arr: [Int]) {
if arr.count == n /2 { ret.append(arr); return }
var arr = arr
for i in0..<6 {
arr.append(i)
dfs(arr)
arr.removeLast()
}
}
dfs([])
return ret
}
// 각 조합에 따른 합산funcsumDices(_picks: [[Int]], _dices: [Int]) -> [Int] {
var ret = [Int]()
for pick in picks {
var value =0for (p, d) inzip(pick, dices) {
value += dice[d][p]
}
ret.append(value)
}
return ret
}
// 합산을 토대로 이분탐색으로 확인funccountWin(_A: [Int], _B: [Int]) -> Int {
var result =0, A=A, B=BA.sort()
B.sort()
for a inA {
var start =0, end =B.count -1while start <= end {
let mid = (start + end) /2if a >B[mid] {
start = mid +1
} else {
end = mid -1
}
}
result += start
}
return result
}
하지만 Swift에서는 시간을 초과가 나게 된다.
합산된 값들을 확인하니 겹치는 숫자들이 많기 때문에 Dictionary로 표현하니 해결됐다.
함수 countWin은 A와 B의 승리하는 횟수를 튜플로 반환한다.
수정된 코드는 아래와 같다.
funcsumDices(_picks: [[Int]], _dices: [Int]) -> [Int: Int] {
var ret = [Int: Int]()
for pick in picks {
var value =0for (p, d) inzip(pick, dices) {
value += dice[d][p]
}
ret[value, default: 0] +=1
}
return ret
}
funccountWin(_A: [Int: Int], _B: [Int: Int]) -> (Int, Int) {
var result = (0, 0)
for aKey inA.keys {
for bKey inB.keys {
if aKey > bKey {
result.0+=A[aKey]!*B[bKey]!
} elseif aKey < bKey {
result.1+=A[aKey]!*B[bKey]!
}
}
}
return result
}
카카오 문제를 보게되면 문제를 잘 읽고 구현만 하면 된다. 시간 초과가 발생하겠지만... 이분 탐색, Dictionary, Queue 등 다양한 방법을 빠르게 해결할 줄 알아야 할 거 같은 문제였다. 나름 고민을 했는데도 시간 초과할 줄이야