1 问题描述
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].
2 思路
用动态规划来解这类问题.
2 3 的二进制数中的个数分别是0 1中二进制个数+1, 4-7中的二进制数目是0-3中二进制数目+1,依次类推.按照这种思路的代码.
class Solution {
public:
vector<int> countBits(int num) {
vector<int> res;
res.push_back(0);
res.push_back(1);
if(num==1)
return res;
int alpha=2*2;
for(int i=2;i<=num;++i){
if(i==alpha){
alpha=2*alpha;
}
res.push_back(res[i%(alpha/2)]+1);
}
return res;
}
};
另外一种思路.
class Solution {
public:
vector<int> countBits(int num) {
vector<int> ret(num+1, 0);
for (int i = 1; i <= num; ++i)
ret[i] = ret[i&(i-1)] + 1;
return ret;
}
};
其中比较trick的地方是ret[i&i-1]这一步.
假设i的二进制最后一位向前有n>=0连续的0,那么倒数第n+1位为1,与n-1按位与后这n+1位一定变为0,前面的不变,因此1的个数必定会减少1.也即 ret[i] = ret[i&(i-1)] + 1成立.
时间和空间复杂度都是O(n).