打表找规律-灯泡状态数

题目:leetcode 672

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:

Flip all the lights.
Flip lights with even numbers.
Flip lights with odd numbers.
Flip lights with (3k + 1) numbers, k = 0, 1, 2, 

打表器

def go(li, op):
    if op == 0:
        ans = [1 ^ int(i) for i in li]
    if op == 1:
        ans = [1 ^ int(li[i]) if i % 2 == 0 else li[i] for i in range(len(li))]
    if op == 2:
        ans = [1 ^ int(li[i]) if i % 2 == 1 else li[i] for i in range(len(li))]
    if op == 3:
        ans = [1 ^ int(li[i]) if i % 3 == 0 else li[i] for i in range(len(li))]
    return ''.join(map(lambda x:str(x),ans))


def flipLights(n, m):
    """
    :type n: int
    :type m: int
    :rtype: int
    """
    ans = set()
    ans.add('1' * n)
    for i in range(m): 
        temp = set()
        for x in ans:
            for i in range(4):
                son = go(x, i)
                temp.add(son)
        ans = temp
    return len(ans)


for n in range(1, 100):
    for m in range(1, 100):
        print(flipLights(n, m), end=' ')
    print()

最终结果

        if m==0:return 1
        elif n==1:
            return 2
        elif n==2:
            if m==1:
                return 3
            else:
                return 4
        else:
            if m==1:
                return 4
            elif m==2:
                return 7
            else:return 8
原文地址:https://www.cnblogs.com/weiyinfu/p/7469165.html