Bulb Switcher II

https://leetcode.com/problems/bulb-switcher-ii/discuss/

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, ...

Thoughts

一共四种操作. 首先不难注意到对同一操作执行偶数次, 那么相当于没有做该操作. 比如22223, 相当于只做了3. 因此无论m为多少, 本质上留下的状态也就是这四种单个操作可能组合所生成的效果, 也就是1,12, 13, 14, 123, 134, 2, 23, 24, 234, 3, 34, 4等十三种操作组合产生的效果外加o, 即原始状态. 不难看出12 == 3, 13 == 2, 23 == 1, 因此123 == 33 == o, 134 == 24, 234 == 14, 抛去这6种最后剩下o, 1, 2, 3, 4, 14, 24, 34这8种效果. 再对n和m分类讨论下即可.

Code

class Solution {
    public int flipLights(int n, int m) {
        if (m == 0) {
            return 1;
        }
        if (n == 1) {
            // o可以是亮或灭
            return 2;
        }
        if (n == 2 && m == 1) {
            return 3;
        }
        if (n == 2) {
            return 4;
        }
        if (m == 1) {
            return 4; // 对应1, 2, 3, 4操作
        }
        if (m == 2) {
            return 7; // 对应 o, 14, 24, 34, 12 = 3, 13 = 2, 23 = 1
        }
        return 8;          
    }
}

Analysis

时空复杂度O(1)

Last updated