一、题目说明
题目338. Counting Bits,给定一个正整数n,返回从0-n之间所有数组对应二进制数包含1的个数。难度是Medium!复杂度要求是O(n)。
二、我的解答
这个题目用dp,其实是非常简单的:
class Solution{
public:
vector<int> countBits(int num){
vector<int> res(num+1,0);
if(num>0) res[1]=1;
for(int i=2;i<=num;i++){
int tmp = i%2;
res[i] = res[i/2] + tmp;
}
return res;
}
};
性能如下:
Runtime: 52 ms, faster than 93.90% of C++ online submissions for Counting Bits.
Memory Usage: 9.6 MB, less than 63.42% of C++ online submissions for Counting Bits.
三、优化措施
无