灯的开关 Bulb Switcher II
為什么80%的碼農(nóng)都做不了架構(gòu)師?>>> ??
問題:
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:
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].
解決:
① 還是找規(guī)律。
我們只需要考慮當(dāng) n<=2 and m < 3 的特殊情形。因為當(dāng) n >2 and m >=3, 結(jié)果肯定是 8.
四個按鈕的功能:
- 翻轉(zhuǎn)所有的燈。
- 翻轉(zhuǎn)偶數(shù)的燈。
- 翻轉(zhuǎn)奇數(shù)的燈。
- 翻轉(zhuǎn)(3k + 1)數(shù)字,k = 0,1,2,...
如果我們使用按鈕1和2,則等同于使用按鈕3。
同樣的:
1 + 2 → 3,1 + 3 → 2,2 + 3 → 1
所以,只有8種結(jié)果:1,2,3,4,1 + 4,2 + 4,3 + 4,當(dāng)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)數(shù)學(xué)問題,總共有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 {//8mspublic 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;} }轉(zhuǎn)載于:https://my.oschina.net/liyurong/blog/1606467
總結(jié)
以上是生活随笔為你收集整理的灯的开关 Bulb Switcher II的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SqlCommand.Parameter
- 下一篇: 案例解读:小红书邂逅AWS,轻松玩转社区