[leetcode] 672. Bulb Switcher II

441 篇文章 0 订阅
284 篇文章 0 订阅

Description

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:

  1. Flip all the lights.
  2. Flip lights with even numbers.
  3. Flip lights with odd numbers.
  4. 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].

分析

题目的意思是:
有n个灯,我按照规则做m次开关操作,求这n个灯最后的种类数

这道题最多只有8种情况(我不知道怎么的出来的),所以很适合分情况来讨论:

  1. 当m和n其中有任意一个数是0时,返回1

  2. 当n = 1时,只有两种情况,0和1

  3. 当n = 2时,这时候要看m的次数,如果m = 1,那么有三种状态 00,01,10

  4. 当m > 1时,那么有四种状态,00,01,10,11

  5. 当m = 1时,此时n至少为3,那么我们有四种状态,000,010,101,011

  6. 当m = 2时,此时n至少为3,我们有七种状态:111,101,010,100,000,001,110

  7. 当m > 2时,此时n至少为3,我们有八种状态:111,101,010,100,000,001,110,011

代码

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;
    }
};

参考文献

[LeetCode] Bulb Switcher II 灯泡开关之二

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值