338.比特位计数
对于二进制来说,所有2的幂次位1的个数都为1,所以我们先将所有2的幂次位置一,对于所有非2的幂次位来说规律就是
res[j]=res[begin]+res[j-begin] (begin是j之前2的幂次位)
class Solution {
public:
vector<int> countBits(int num) {
vector<int>res(num+1);
for (int i = 0; pow(2,i)<=num ; ++i) {
res[pow(2,i)]=1;
}
int begin=2;
for (int j = 3; j <res.size() ; ++j) {
if (res[j]==1)
begin=j;
else
res[j]=res[j-begin]+res[begin];
}
return res;
}
};