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.
Suppose n
lights are labeled as number [1, 2, 3 …, n], function of these 4 buttons are given below:
- Flip all the lights.
- Flip lights with even numbers.
- Flip lights with odd numbers.
- Flip lights with (3k + 1) numbers, k = 0, 1, 2, …
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: n
and m
both fit in range [0, 1000].
Solution1: Bitmask + Simulation
The light pattern will be repeated if we have more than 6 lights, so n = n % 6, n = 6 if n == 0.
Time complexity: O(m*2^6)
Space complexity: O(2^6)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
// Author: Huahua class Solution { public: int flipLights(int n, int m) { if (n > 6) n = n % 6 + 6; unordered_set<int> s1{(1 << n) - 1}; auto flip = [n](int s, int start, int step) { for (int i = start; i < n; i += step) s ^= (1 << i); return s; }; for (int i = 0; i < m; ++i) { unordered_set<int> s2; for (int s : s1) { s2.insert(flip(s, 0, 1)); s2.insert(flip(s, 0, 2)); s2.insert(flip(s, 1, 2)); s2.insert(flip(s, 0, 3)); } s1.swap(s2); } return s1.size(); } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment