您的位置:首页 > 编程语言 > Python开发

338. Counting Bits -Medium

2017-02-06 19:27 204 查看

Question

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.

给出一个非负整数num,对[0, num]范围内的数分别计算它们的二进制数中1的个数,用数组形式返回。

Example

For num = 5 you should return [0,1,1,2,1,2].

Solution

动态规划解。其实这是道找规律的题目,我们首先列出0-15的数对应的二进制中1的个数

数字二进制中1的个数递推关系式
00dp[0] = 0
11dp[1] = dp[1-1] + 1
21dp[2] = dp[2-2] + 1
32dp[3] = dp[3-2] + 1
41dp[4] = dp[4-4] + 1
52dp[5] = dp[5-4] + 1
62dp[6] = dp[6-4] + 1
73dp[7] = dp[7-4] + 1
81dp[8] = dp[8-8] + 1
92dp[9] = dp[9-8] + 1
102dp[10] = dp[10-8] + 1
113dp[11] = dp[11-8] + 1
122dp[12] = dp[12-8] + 1
133dp[13] = dp[13-8] + 1
143dp[14] = dp[14-8] + 1
154dp[15] = dp[15-8] + 1
综上,递推关系式为 dp
= dp[n - offset] + 1
(这个规律还真不怎么好找),而offset的更新规律为,每当 offset * 2等于n时,offset就需要更新,即乘以2.

class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
# 0-num有num + 1个数
dp = [0] * (num + 1)
offset = 1
for n in range(1, num + 1):
# 根据规律,只要index = 2 * offset,offset需要乘以2
if offset * 2 == n:
offset *= 2
# dp[index] = dp[index - offset] + 1
dp
= dp[n - offset] + 1
return dp
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息