题目描述
Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1’s in the binary representation of i.
解题思路
看到时间复杂度限制,首先想到DP。难点在于如何找到递推式子。对于一个二进制的数字比如,1001,其实我们可以看出,如果把最高位的 1 去掉,那么其就变成 001 (也就是 1),那么这个结果如果我们可以从之前的计算中直接得到那么 1001 包含 1 的个数就是 最高位 1 + dp[1]。在实现过程中我们需要保存当前的最高位的阶数。
代码
class Solution:
def countBits(self, n: int) -> List[int]:
dp = [0] * 100001
divide = [pow(2, i) for i in range(20)]
base = 0
for i in range(1, 100001):
if i in divide:
dp[i] = 1
base += 1
if i % 2 == 1:
dp[i] = dp[i - 1] + 1
else:
tmp = i - pow(2, base - 1)
dp[i] = 1 + dp[tmp]
return dp[:n + 1]