题目如下:
There is a room with
n
bulbs, numbered from0
ton-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
wheretarget[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
ton-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: 0Example 4:
Input: target = "001011101" Output: 5Constraints:
1 <= target.length <= 10^5
target[i] == '0'
ortarget[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]