首页 > 代码库 > LeetCode 338. Counting Bits
LeetCode 338. Counting Bits
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.
公众号每日一题有详细讲解分析:
P 题的难点在于构建最优子结构。只要构造了最优子结构,一般就比较容易解题了。构造最优子结构的方法有两种:倒推发现 n 与 0 到 n - 1 的关系;使用 DFS 和 递归 方法,从 0 到 n 发现规律。
今天这道题的解法试图通过观察其特点发现规律。这也是一般性的思考问题的方法:通过画图,将抽象的问题具体化,通过具体的例子来发现规律,最后推广到 n 的规模。
class Solution { public: vector<int> countBits(int num) { vector<int> res(num + 1, 0); res[1] = 1; for ( int i = 0; i <= num; i++) { if ( i % 2 == 0) { res[i] = res[i/2]; } else { res[i] = res[i/2] + 1; } } return res; } };
class Solution { public: vector<int> countBits(int num) { vector<int> res(num + 1, 0); for ( int i = 1; i <= num; i++) { res[i] = res[i >> 1] + (i & 1); } return res; } };
LeetCode 338. Counting Bits