Bulb Switcher II问题及解法

问题描述:

There is a room with n lights which are turned on initially and 4 buttons on the wall. After performing exactly munknown 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, ...

示例:

Input: n = 1, m = 1.
Output: 2
Explanation: Status can be: [on], [off]
Input: n = 2, m = 1.
Output: 3
Explanation: Status can be: [on, off], [off, on], [off, off]
Input: n = 3, m = 1.
Output: 4
Explanation: Status can be: [off, on, off], [on, off, on], [off, off, off], [off, on, on].

问题分析:

这类问题实际上就是找规律,我也不多说什么了,上大神的讲解

1: light is on
0: light is off

n == 1

Only 2 possibilities: 1 and 0.

n == 2

After one operation, it has only 3 possibilities: 0010 and 01.
After two and more operations, it has only 4 possibilities: 111001 and 00.

n == 3

After one operation, it has only 4 possibilities: 000101010 and 011.
After two operations, it has 7 possibilities: 111,101,010,100,000,001 and 110.
After three and more operations, it has 8 possibilities, plus 011 on above case.

n >= 4

After one operation, it has only 4 possibilities: 000010100101 and 0110.
After two or more operations: it has 8 possibilities, 1111,1010,0101,0111,0000,00111100 and 1001.

实际上,这个题灯的状态在该集合中{all_on,1,2,3,4,1+4,2+4,3+4}.


过程详见代码:

class Solution {
public:
    int flipLights(int n, int m) {
        if (m == 0) return 1;
		if (n <= 0 || m < 0) return 0;
		if (n == 1) return 2;
		else if (n == 2) return (m == 1) ? 3 : 4;
		else return (m == 1) ? 4 : ((m == 2) ? 7 : 8);
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值