問題: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; } }