开关灯问题 BulbSwitch

2018-06-17 11:54:51

开关电灯问题是一个比较经典的趣味数学题,本文中主要介绍其中的一些常见情况。

一、Bulb Switch

问题描述:

问题求解:

初始状态:off, off, off,... ,off.

Step 1:on, on, on, ... ,on

Step 2:on, off, on, ...

对于第 i 盏灯,其在Step k 被switch前提是i % k == 0。因此,对于第 i 盏灯其在最后保持on的前提是其因子个数为奇数个,换言之,i 只有是完全平方数才能满足条件。所以本题就转换成了求完全平方数个数的问题。

public class BulbSwitch {
    public int bulbSwitch(int n) {
        return (int) Math.sqrt(n);
    }
}

二、Bulb Switcher II

问题描述:

问题求解:

首先研究一下其中的操作,可以发现1 + 3 - > 2,1 + 2 - > 3, 2 + 3 - > 1。因此实际上至多只会产生如下8种可能:

All_on, 1, 2, 3, 4, 1+4, 2+4, 3+4

用二进制表示就是000~111的八种表示。

要得到这八种结果需要至少三次操作,因此m >= 3,另外当n < 3 的时候显然是无法得到8中结果的,因此对于m < 3 && n < 3 的情况做一下讨论即可。

class Solution {
    public int flipLights(int n, int m) {
        if(m==0) return 1;
        if(n==1) return 2;
        if(n==2&&m==1) return 3;
        if(n==2) return 4;
        if(m==1) return 4;
        if(m==2) return 7;
        if(m>=3) return 8;
        return 8;
    }
}
原文地址:https://www.cnblogs.com/hyserendipity/p/9192588.html