在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ There is a room with Suppose
Example 1: Input: n = 1, m = 1. Output: 2 Explanation: Status can be: [on], [off] Example 2: Input: n = 2, m = 1. Output: 3 Explanation: Status can be: [on, off], [off, on], [off, off] Example 3: Input: n = 3, m = 1. Output: 4 Explanation: Status can be: [off, on, off], [on, off, on], [off, off, off], [off, on, on]. Note: 现有一个房间,墙上挂有 假设这
示例 1: 输入: n = 1, m = 1. 输出: 2 说明: 状态为: [开], [关] 示例 2: 输入: n = 2, m = 1. 输出: 3 说明: 状态为: [开, 关], [关, 开], [关, 关] 示例 3: 输入: n = 3, m = 1. 输出: 4 说明: 状态为: [关, 开, 关], [开, 关, 开], [关, 关, 关], [关, 开, 开]. 注意: Runtime: 4 ms
Memory Usage: 18.9 MB
1 class Solution { 2 func flipLights(_ n: Int, _ m: Int) -> Int { 3 var n = min(n, 3) 4 return min(1 << n, 1 + m * n) 5 } 6 } 4ms 1 class Solution { 2 struct State: Hashable, OptionSet { 3 let rawValue: Int 4 5 static let oddSensitive = State(rawValue: 1) 6 static let evenInsensitive = State(rawValue: 2) 7 static let oddInsensitive = State(rawValue: 4) 8 static let evenSensitive = State(rawValue: 8) 9 10 static let odd: State = [.oddSensitive, .oddInsensitive] 11 static let even: State = [.evenSensitive, .evenInsensitive] 12 static let sensitive: State = [.evenSensitive, .oddSensitive] 13 14 static let all: State = [.oddSensitive, .oddInsensitive, .evenSensitive, .evenInsensitive] 15 } 16 17 func flipLights(_ n: Int, _ m: Int) -> Int { 18 let mask = State(rawValue: 1 << min(n, 4) - 1) 19 let permittedCount = Set<Int>(0...4).filter { $0 <= m && ($0 % 2) == (m % 2) } 20 21 var states = Set<State>() 22 23 for i in 0..<16 { 24 var count = 0, state = State.all 25 if (i & 1) != 0 { 26 state.formSymmetricDifference(.all) 27 count += 1 28 } 29 if (i & 2) != 0 { 30 state.formSymmetricDifference(.even) 31 count += 1 32 } 33 if (i & 4) != 0 { 34 state.formSymmetricDifference(.odd) 35 count += 1 36 } 37 if (i & 8) != 0 { 38 state.formSymmetricDifference(.sensitive) 39 count += 1 40 } 41 42 if permittedCount.contains(count) { 43 states.insert(state.intersection(mask)) 44 } 45 } 46 47 return states.count 48 } 49 }
|
请发表评论