首页 > 学院 > 开发设计 > 正文

338. Counting Bits -Medium

2019-11-11 05:06:34
字体:
来源:转载
供稿:网友

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的个数 递推关系式
0 0 dp[0] = 0
1 1 dp[1] = dp[1-1] + 1
2 1 dp[2] = dp[2-2] + 1
3 2 dp[3] = dp[3-2] + 1
4 1 dp[4] = dp[4-4] + 1
5 2 dp[5] = dp[5-4] + 1
6 2 dp[6] = dp[6-4] + 1
7 3 dp[7] = dp[7-4] + 1
8 1 dp[8] = dp[8-8] + 1
9 2 dp[9] = dp[9-8] + 1
10 2 dp[10] = dp[10-8] + 1
11 3 dp[11] = dp[11-8] + 1
12 2 dp[12] = dp[12-8] + 1
13 3 dp[13] = dp[13-8] + 1
14 3 dp[14] = dp[14-8] + 1
15 4 dp[15] = dp[15-8] + 1

综上,递推关系式为 dp[n] = 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[n] = dp[n - offset] + 1 return dp
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表