LeetCode 600
Brute force 的方法,遍历所有数字,查看是否有连续的1.
def findIntegersTimeout(self, num: int) -> int:
if num < 0: return 0
if num == 0: return 1
result = 0
for i in range(0, num+1):
if Solution.obeyRule(i):
result +=1
return result
@staticmethod
def obeyRule(num: int) -> int:
if (num & (num >> 1)) == 0:
return True
else:
return False
结果是time out,还是不够好。
改用DP:如果把小于n个bit的10000…的结果记做dp【n】,那么小于他的结果可以分为几类:
010xxxx =》 只能是小于001000…的是符合的数,可以记做dp【n-2】
011xxxx(不符合,忽略)
00xxxxx =》 只能是小010000…的符合的数,记做dp【n-1】
所以有公式:dp【n】=dp【n-1】+dp【n-2】
显然:
dp【0】 = 1
dp【1】 = 2,
这样我们可以的得到dp【n】
对于任意num,最高位比如是1,所以可以分为:
- 开始于11,然后xxxx,这个显然所有大于11000…都不成立,只需要知道dp【n】就够了
- 开始于10,然后xxx,那么再分:
2.1 所有小于01…的结果 dp【n-1】
2.2 大于10…的结果,那么去掉前面的“10”之后剩下的部分,可以递归求解。
from typing import List
import collections
class Solution:
def findIntegers(self, num: int) -> int:
numStr = bin(num)[2:]
n = len(numStr)
dp = [1, 2]
for i in range(2, n+1):
dp.append(dp[i-1] + dp[i-2])
return Solution.helper(numStr, dp)
@staticmethod
def helper(num:str, dp: List[int]) -> int:
result = 1
n = len(num)
prefix = num[0:2]
if prefix == "11":
result = dp[n]
elif prefix == "10":
result = dp[n-1] + Solution.helper(num[2:].lstrip('0'), dp)
elif prefix == "1":
result +=1
return result