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.
解题思路:动态规划,dp[i]代表数字i的二进制含有多少个1
如果i是奇数的话,i-1是偶数,那个i-1的二进制的最低位一定是0,加1并不会进位,所以dp[i] = dp[i-1]+1
如果i是偶数的话,i会与i/2的二进制拥有相同个数的1,因为i/2左移一位,最后补0,就是i,所以dp[i] = dp[i/2]
class Solution {
public:
vector<int> countBits(int num) {
vector<int> dp(num+1,0);
for (int i = 1; i <= num; i++) {
if (i%2==0) {
dp[i] = dp[i/2];
} else {
dp[i] = dp[i-1]+1;
}
}
return dp;
}
};
本文介绍了一种使用动态规划方法来计算从0到给定整数范围内每个数的二进制表示中1的数量的方法,并提供了一个具体的实现示例。


被折叠的 条评论
为什么被折叠?



