题目:
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].
思路:
n小于等于1的时候,属于平凡情况,可以直接返回。对于这四种类型的操作,我们可以得出如下的观察结论:
1)对于每种类型的操作,每操作两次就等于没有操作,所以其操作结果只与其操作次数的奇偶性有关。
2)前三种操作可以被规约为1次或者0次操作。例如,操作1和操作2的结果就等于操作3,而操作1,操作2和操作3的结果就是保持原貌。
3)对于n > 3的情况,其结果与n == 3的情况相同,因为当前3个灯泡的状态确定之后,后面的所有的灯泡的状态都是确定的。
所以,我们可以将所有的情况规约为m <= 3, n <= 3的情况。所以就可以直接返回结果了,时间复杂度和空间复杂度都是O(1)。
代码:
class Solution {
public:
int flipLights(int n, int m) {
if (m == 0 || n == 0) {
return 1;
}
if (n == 1) {
return 2;
}
if (n == 2) {
return m == 1 ? 3 : 4;
}
if (m == 1) {
return 4;
}
return m == 2 ? 7 : 8;
}
};