按照提示,时间O(n) 空间 O(n),从头到尾扫一遍。
还有待优化的是,使用pow函数,比较费时。
AC代码
class Solution {
public:
vector<int> countBits(int num) {
vector<int> ret(num+1, 0);
int i, j;
for(i = 0; pow(2,i) <= num; ++i)
{
for(j = 0; j < pow(2,i) && pow(2,i)+j <= num; ++j) //care of the bound
{
ret[pow(2,i)+j] = ret[j] + 1;
}
}
return ret;
}
};