【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]
复制代码

 

posted @   seyjs  阅读(203)  评论(0编辑  收藏  举报
编辑推荐:
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
阅读排行:
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(四):结合BotSharp
· 《HelloGitHub》第 108 期
· Windows桌面应用自动更新解决方案SharpUpdater5发布
· 我的家庭实验室服务器集群硬件清单
· Supergateway:MCP服务器的远程调试与集成工具
历史上的今天:
2019-09-14 【leetcode】1172. Dinner Plate Stacks
2016-09-14 【crontab】误删crontab及其恢复
点击右上角即可分享
微信分享提示