338 . 比特位计数

338 . 比特位计数

给定一个非负整数 num。对于 0 ≤ i ≤ num 范围中的每个数字 i ,计算其二进制数中的 1 的数目并将它们作为数组返回。

示例 1:

输入: 2
输出: [0,1,1]
示例 2:

输入: 5
输出: [0,1,1,2,1,2]
进阶:

给出时间复杂度为O(n*sizeof(integer))的解答非常容易。但你可以在线性时间O(n)内用一趟扫描做到吗?
要求算法的空间复杂度为O(n)。
你能进一步完善解法吗?要求在C++或任何其他语言中不使用任何内置函数(如 C++ 中的 __builtin_popcount)来执行此操作。

Given an integer num, return an array of the number of 1's in the binary representation of every number in the range [0, num].

Example 1:

Input: num = 2
Output: [0,1,1]
Explanation:
0 --> 0
1 --> 1
2 --> 10
Example 2:

Input: num = 5
Output: [0,1,1,2,1,2]
Explanation:
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101

Constraints:

0 <= num <= 105

Follow up:

It is very easy to come up with a solution with run time O(32n). Can you do it in linear time O(n) and possibly in a single pass?
Could you solve it in O(n) space complexity?
Can you do it without using any built-in function (i.e., like __builtin_popcount in C++)?

分析

题目要返回 0 ~ n 中每一个数的二进制中含有多少个 1
最先想到的方法就是每次都计算出这个二进制数 , 然后统计出其中有多少个 1 
或者是找到这个数组有什么规律
标题是位运算和动态规划 , 所以我们如果借助指针看这个数每一位上是不是 1 是否可行呢 ?
动态规划我还没有学过 , 现在可以了解一下
原文地址:https://www.cnblogs.com/karlshuyuan/p/14642076.html