Leetcode leetcode 672. Light bulb switch Ⅱ

insert image description here

Topic link and description

https://leetcode.cn/problems/bulb-switcher-ii/
There are n turned on bulbs in the room, numbered from 1 to n. There are 4 switches hanging on the wall.

Each of the 4 switches has a different function, among them:

Switch 1: Reverse the state of all current lights (i.e. on to off, off to on)
Switch 2: Reverse the state of even numbered lights (i.e. 2, 4, ...)
Switch 3: Reverse the number to odd numbers State of the lamps (i.e. 1, 3, ...)
Switch 4: Inverts the state of the lamps numbered j = 3k + 1, where k = 0, 1, 2, ... (i.e. 1, 4, 7, 10, ... )
you have to press the switch presses exactly times. Each time you press, you need to choose one of the 4 switches to perform the press.

Given two integers n and presses, after performing all presses, return the number of different possible states.

Example 1:

Input: n = 1, presses = 1
Output: 2
Explanation: The state can be:

  • Press switch 1, [OFF]
  • Press switch 2, [ON]
    Example 2:

Input: n = 2, presses = 1
Output: 3
Explanation: The state can be:

  • Press switch 1, [OFF, OFF]
  • Press switch 2, [ON, OFF]
  • Press switch 3, [OFF, ON]
    Example 3:

Input: n = 3, presses = 1
Output: 4
Explanation: States can be:

  • Press switch 1, [OFF, OFF, OFF]
  • Press switch 2, [OFF, ON, OFF]
  • Press switch 3, [ON, ON, ON]
  • Press switch 4, [OFF, ON, ON]

hint:

1 <= n <= 1000
0 <= presses <= 1000

Key words: truth table to find the law

The number of switches is limited and the variable space is limited

The first switch is k;
the second switch is 2k;
the third switch is 2k-1;
the third switch is 3k+1;

So 6 is his period, you only need to enumerate his truth table to get the answer~

method one:

run screenshot

insert image description here

the code


    public int flipLights(int n, int presses) {
    
    
        //不按开关
        if (presses == 0) {
    
    
            return 1;
        }
        //特殊情况处理
        if (n == 1) {
    
    
            return 2;
        } else if (n == 2) {
    
    
            //特殊情况
            return presses == 1 ? 3 : 4;
        } else {
    
    
            //n >= 3
            return presses == 1 ? 4 : presses == 2 ? 7 : 8;
        }
    }

end

Welcome to communicate in the comment area, check in every day, and rush! ! !

Guess you like

Origin blog.csdn.net/qq_35530042/article/details/126879145