美文网首页
672. Bulb Switcher II

672. Bulb Switcher II

作者: 尚无花名 | 来源:发表于2019-03-11 00:00 被阅读0次

    这道题看上去很吓人。
    但是观察发现由于操作时总是几个灯泡一起操作,所以必然有不少灯泡的状态是锁定的。
    最多只有6个状态独立的灯泡。
    所以n可以转换成min(n, 6)
    然后对于同一个操作, 执行 0次和2次效果是一样的, 执行1次和3次效果是一样的。
    而且不同操作之间是可以互换的。
    所以他们是相互独立的而且没有先后顺序的。
    有四种操作,每种操作执行0次或者一次。
    我们可以用bfs从0出发看 一共有多少种状态。最后会遇到一个循环。这样处理有点麻烦。

    但最多有16种状态,索性我们就看每种状态哪种状态在m步里可以到吧
    只要奇偶数match,和需要set为1的位数大于等于m这个状态就可以到 。

    class Solution {
        public int flipLights(int n, int m) {
            n = Math.min(6, n);
            Set<Integer> seen = new HashSet<>();
            int shift = 6 - n;
            for (int cand = 0; cand < 16; ++cand) {
                int bCount = Integer.bitCount(cand);
                if (bCount % 2 != m % 2 || bCount > m) continue;
                int lights = 0;
                // simulate
                if (((cand >> 0) & 1 ) > 0 ) lights ^= (0b111111 >> shift);
                if (((cand >> 1) & 1 ) > 0 ) lights ^= (0b101010 >> shift);
                if (((cand >> 2) & 1 ) > 0 ) lights ^= (0b010101 >> shift);
                if (((cand >> 3) & 1 ) > 0 ) lights ^= (0b100100 >> shift);
                seen.add(lights);
            }
            return seen.size();
        }
    }
    

    相关文章

      网友评论

          本文标题:672. Bulb Switcher II

          本文链接:https://www.haomeiwen.com/subject/frumpqtx.html