0
点赞
收藏
分享

微信扫一扫

【每日算法Day 61】LeetCode 672. 灯泡开关 Ⅱ


题目描述

【每日算法Day 61】LeetCode 672. 灯泡开关 Ⅱ_python

示例1

输入:
n = 1, m = 1.
输出:
2
解释:
状态为: [开], [关]

示例2

输入:
n = 2, m = 1.
输出:
3
解释:
状态为: [开, 关], [关, 开], [关, 关]

示例3

输入:
n = 3, m = 1.
输出:
4
解释:
状态为: [关, 开, 关], [开, 关, 开], [关, 关, 关], [关, 开, 开].

提示

【每日算法Day 61】LeetCode 672. 灯泡开关 Ⅱ_c++_02

题解

【每日算法Day 61】LeetCode 672. 灯泡开关 Ⅱ_c++_03【每日算法Day 61】LeetCode 672. 灯泡开关 Ⅱ_python_04

代码

c++


class Solution {
public:
int flipLights(int n, int m) {
if (m == 0) return 1;
if (n == 1) return 2;
m = min(m, 3);
if (n == 2) return vector<int>{3, 4, 4}[m-1];
return vector<int>{4, 7, 8}[m-1];
}
};


python


class Solution:
def flipLights(self, n: int, m: int) -> int:
if m == 0: return 1
if n == 1: return 2
m = min(m, 3)
if n == 2: return [3, 4, 4][m-1]
return [4, 7, 8][m-1]


python(枚举)


class Solution:
def flipLights(self, n, m):
seen = set()
for cand in itertools.product((0, 1), repeat = 4):
if sum(cand) % 2 == m % 2 and sum(cand) <= m:
A = []
for i in range(min(n, 3)):
light = 1
light ^= cand[0]
light ^= cand[1] and i % 2
light ^= cand[2] and i % 2 == 0
light ^= cand[3] and i % 3 == 0
A.append(light)
seen.add(tuple(A))
return len(seen)


举报

相关推荐

0 条评论