• 【leetcode】1529. Bulb Switcher IV


    题目如下:

    There is a room with n bulbs, numbered from 0 to n-1, arranged in a row from left to right. Initially all the bulbs are turned off.

    Your task is to obtain the configuration represented by target where target[i] is '1' if the i-th bulb is turned on and is '0' if it is turned off.

    You have a switch to flip the state of the bulb, a flip operation is defined as follows:

    • Choose any bulb (index i) of your current configuration.
    • Flip each bulb from index i to n-1.

    When any bulb is flipped it means that if it is 0 it changes to 1 and if it is 1 it changes to 0.

    Return the minimum number of flips required to form target.

    Example 1:

    Input: target = "10111"
    Output: 3
    Explanation: Initial configuration "00000".
    flip from the third bulb:  "00000" -> "00111"
    flip from the first bulb:  "00111" -> "11000"
    flip from the second bulb:  "11000" -> "10111"
    We need at least 3 flip operations to form target.

    Example 2:

    Input: target = "101"
    Output: 3
    Explanation: "000" -> "111" -> "100" -> "101".
    

    Example 3:

    Input: target = "00000"
    Output: 0
    

    Example 4:

    Input: target = "001011101"
    Output: 5

    Constraints:

    • 1 <= target.length <= 10^5
    • target[i] == '0' or target[i] == '1'

    解题思路:记dp[i] = v 为经过v次的开关后,使得0~i这个子区间的灯泡满足target的需求。对于任意一个灯泡i来说,其开关的次数只与i-1的开关次数有关。如果当前第i-1个灯泡开关了n次,那么显然第i个灯泡也开关了n次,只要判断n次之后i灯泡的状态是否满足target的要求,如果满足,则dp[i] = dp[i-1],不满足的话则有dp[i] = dp[i-1]+1。

    代码如下:

    class Solution(object):
        def minFlips(self, target):
            """
            :type target: str
            :rtype: int
            """
            dp = [0] * len(target)
            dp[0] = 0 if target[0] == '0' else 1
            for i in range(1,len(target)):
                if dp[i-1] % 2 == 0:
                    dp[i] = dp[i-1] if target[i] == '0' else dp[i-1] + 1
                else:
                    dp[i] = dp[i-1] if target[i] == '1' else dp[i-1] + 1
            #print dp
            return dp[-1]
  • 相关阅读:
    关于EF中实体和数据表以及查询语句映射的问题
    流程设计(流程上下文法)
    流程设计(抽象节点法)
    第六章 跑马灯实验
    如何批量导入excel数据至数据库(MySql)--工具phpMyAdmin
    win10卸载瑞星
    如何在sublime上运行php
    Pycharm+django新建Python Web项目
    部署Asp.net Core 项目发生502.5 或者500 没有其他提示信息
    常用Windows DOS命令项目部署经常用到
  • 原文地址:https://www.cnblogs.com/seyjs/p/13667084.html
Copyright © 2020-2023  润新知