-
Notifications
You must be signed in to change notification settings - Fork 888
/
FlipGameII.swift
39 lines (31 loc) · 1009 Bytes
/
FlipGameII.swift
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
32
33
34
35
36
37
38
39
/**
* Question Link: https://leetcode.com/problems/flip-game-ii/
* Primary idea: Classic DP, using a map to memorize previous step
* Time Complexity: O(n), Space Complexity: O(n)
*/
class FlipGameII {
func canWin(_ s: String) -> Bool {
var winMap = [String: Bool]()
return helper(s, &winMap)
}
func helper(_ s: String, _ winMap: inout [String: Bool]) -> Bool {
guard s.count >= 2 else {
return false
}
if let sWin = winMap[s] {
return sWin
}
let sChars = Array(s)
for i in 0..<sChars.count - 1 {
guard sChars[i] == sChars[i + 1] && sChars[i] == "+" else {
continue
}
if !helper(String(sChars[0..<i] + "--" + sChars[i + 2..<sChars.count]), &winMap) {
winMap[s] = true
return true
}
}
winMap[s] = false
return false
}
}