★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-sdmcianz-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
There is a room with n
lights which are turned on initially and 4 buttons on the wall. After performing exactly m
unknown operations towards buttons, you need to return how many different kinds of status of the n
lights could be.git
Suppose n
lights are labeled as number [1, 2, 3 ..., n], function of these 4 buttons are given below:github
Example 1:微信
Input: n = 1, m = 1. Output: 2 Explanation: Status can be: [on], [off]
Example 2:spa
Input: n = 2, m = 1. Output: 3 Explanation: Status can be: [on, off], [off, on], [off, off]
Example 3:code
Input: n = 3, m = 1. Output: 4 Explanation: Status can be: [off, on, off], [on, off, on], [off, off, off], [off, on, on].
Note: n
and m
both fit in range [0, 1000].orm
現有一個房間,牆上掛有 n
只已經打開的燈泡和 4 個按鈕。在進行了 m
次未知操做後,你須要返回這 n
只燈泡可能有多少種不一樣的狀態。htm
假設這 n
只燈泡被編號爲 [1, 2, 3 ..., n],這 4 個按鈕的功能以下:blog
3k+1
的燈泡的狀態反轉(k = 0, 1, 2, ...)示例 1:ip
輸入: n = 1, m = 1. 輸出: 2 說明: 狀態爲: [開], [關]
示例 2:
輸入: n = 2, m = 1. 輸出: 3 說明: 狀態爲: [開, 關], [關, 開], [關, 關]
示例 3:
輸入: n = 3, m = 1. 輸出: 4 說明: 狀態爲: [關, 開, 關], [開, 關, 開], [關, 關, 關], [關, 開, 開].
注意: n
和 m
都屬於 [0, 1000].
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 }