解法一
所有灯泡的状态都和前四个灯泡有关,同一种操作重复两次也没有意义。由此可以大大缩小数据范围。注意考虑边界情况。
import java.util.HashSet;import java.util.Set;class Solution {Set<Integer> ans;public int flipLights(int n, int m) {// 其他灯泡的状态都可以通过前4个灯泡的状态导出n = Math.min(4, n);// 有效操作最多4次, 每种1次m = Math.min(4, m);switch (n) {case 0:return 0;case 1:if (m == 0) {return 1;} else {return 2;}case 2:if (m == 0) {return 1;} else if(m==1){return 3;}else {return 4;}case 3:switch (m) {case 0:return 1;case 1:return 4;case 2:return 7;default:return 8;}}ans = new HashSet<>();bfs(m, 0b0000);return ans.size();}private void bfs(int m, int status) {if (m == 0) {ans.add(status);return;}bfs(m - 1, 0b1111 ^ status);bfs(m - 1, 0b0101 ^ status);bfs(m - 1, 0b1010 ^ status);bfs(m - 1, 0b1001 ^ status);}}
