Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.
Example:
For num = 5
you should return [0,1,1,2,1,2]
.
一开始是这么做的:
def countBits(self, num):
a=[]
for i in range(num+1):
a.append(bin(i).count('1'))
return a
简单粗暴,但是没有用到动态规划的内容,后来看了下讨论,对答案进行了更正:
动态规划就是找规律,先写出前10个:
0112 1223 1223 2334
dp[0] = 0;
dp[1] = dp[0] + 1;
dp[2] = dp[0] + 1;
dp[3] = dp[1] +1;
dp[4] = dp[0] + 1;
dp[5] = dp[1] + 1;
dp[6] = dp[2] + 1;
dp[7] = dp[3] + 1;
dp[8] = dp[0] + 1;
...
再明显一点就是:
dp[0] = 0;
dp[1] = dp[1-1] + 1;
dp[2] = dp[2-2] + 1;
dp[3] = dp[3-2] +1;
dp[4] = dp[4-4] + 1;
dp[5] = dp[5-4] + 1;
dp[6] = dp[6-4] + 1;
dp[7] = dp[7-4] + 1;
dp[8] = dp[8-8] + 1;
...
即dp[i]=dp[i-offset]+1
当 i=123456789时
offset=12244448
所以offset的初始值为1,当遇到2的n次方数时变为该数
即if offset*2==i
offset*=2
代码如下:
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
a=[0]*(num+1)
offset=1
for i in range(num):
if offset*2==i+1:
offset*=2
a[i+1]=a[i+1-offset]+1
return a