338. Counting Bits(DP)
2017-10-27 11:46
183 查看
1.Description
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].
Follow up:
It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass? Space complexity should be O(n). Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.
2. analysis
这道题其实只要发现二进制数之间的关系,就很容易写出来。我们发现区间[2k,2(k+1)−1] 之间的数 ai 和 ai+1 之间的关系,它们之间的逻辑与的结果是得到相同的高位部分(因为相邻的两个二进制数的最低位不可能相同),如:0110&0111=0110 和0100&0101=0100 和 0101&0110=0100 ,可以看到,ai+1的1的个数要么比 ai 的个数多一个,要么没有,不可能多2个或以上(为什么?so easy)。如果1的个数是相等的,那么ai+1 和 ai 的二进制数的1的个数是基于同一个数(ai可能基于ai−1)递增的,而ai−1 a_能基于 ai−2 如此迭代。而逻辑与的结果是找到离ai 和 ai+1 最近的一个这样的基数,可能是 ai 可能是ai−1 或者 该区间的第一个数,也就是2k。如果ai+1 比 ai 的二进制表示多一个1,那么这个基数就是ai。所以得到状态转移方程是 f(n)=f[n&(n−1)]+13. code
class Solution { public: vector<int> countBits(int num) { // index represents the number vector<int> res(num+1,0); for(int i = 1;i <= num; i++) { res[i] = res[i&(i-1)] + 1; } return res; } };
相关文章推荐
- LeetCode oj 338. Counting Bits(DP)
- LeetCode *** 338. Counting Bits
- Swift 338. Counting Bits
- Leetcode--338. Counting Bits
- LeetCode 338. Counting Bits
- USACO-Section 3.2 Stringsobits(DP)
- leetcode 338. Counting Bits
- [LeetCode]338. Counting Bits
- leetcode解题报告:338. Counting Bits
- 338. Counting Bits
- Leetcode 338. Counting Bits
- LeetCode 338. Counting Bits
- 338. Counting Bits 数字的二进制中1的个数
- leetcode 338. Counting Bits
- LeetCode No338. Counting Bits
- LeetCode 338. Counting Bits
- [Leetcode] 338. Counting Bits 解题报告
- 338. Counting Bits
- 338. Counting Bits
- 338. Counting Bits