问题:spa
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.code
Suppose n
lights are labeled as number [1, 2, 3 ..., n], function of these 4 buttons are given below:orm
Example 1:three
Input: n = 1, m = 1. Output: 2 Explanation: Status can be: [on], [off]
Example 2:ip
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].it
解决:io
① 仍是找规律。function
咱们只须要考虑当 n<=2 and m < 3 的特殊情形。由于当 n >2 and m >=3, 结果确定是 8.form
四个按钮的功能:
- 翻转全部的灯。
- 翻转偶数的灯。
- 翻转奇数的灯。
- 翻转(3k + 1)数字,k = 0,1,2,...
若是咱们使用按钮1和2,则等同于使用按钮3。
一样的:
1 + 2 → 3,1 + 3 → 2,2 + 3 → 1
因此,只有8种结果:1,2,3,4,1 + 4,2 + 4,3 + 4,当n> 2和m> = 3时,咱们能够获得全部的状况。
class Solution { //7ms
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;
}
}
②
//O(1)数学问题,总共有8个state 1111,1010,0101,0111,0000,0011, 1100 and 1001. //须要枚举 n>3之后就只能是这8个state了 //n == 1 Only 2 possibilities: 1 and 0. //n == 2 After one operation, it has only 3 possibilities: 00, 10 and 01. After two and more operations, it has only 4 possibilities: 11, 10, 01 and 00. //n == 3 After one operation, it has only 4 possibilities: 000, 101, 010 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: 0000, 1010, 0101 and 0110. //After two or more operations: it has 8 possibilities, 1111,1010,0101,0111,0000,0011, 1100 and 1001. class Solution {//8ms public int flipLights(int n, int m) { n = Math.min(n, 3); if (m == 0) return 1; if (m == 1) return n == 1 ? 2 : n == 2 ? 3 : 4; if (m == 2) return n == 1 ? 2 : n == 2 ? 4 : 7; return n == 1 ? 2 : n == 2 ? 4 : 8; } }