1. 题目
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/counting-bits/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 思路 (最高有效位 + 动态规划)
当 num = 0 时,temp[0] = 0;
当 num = 1 时,temp[1] = 1;
b = 2^1
当 num = 2 时,temp[2] = temp[2 - 2] + 1 = 1;
当 num = 3 时,temp[3] = temp[3 - 2] + 1 = 2;
b = 2^2
当 num = 4 时,temp[4] = temp[4 - 4] + 1 = 1;
当 num = 5 时,temp[5] = temp[5 - 4] + 1 = 2;
当 num = 6 时,temp[6] = temp[6 - 4] + 1 = 2;
当 num = 7 时,temp[7] = temp[7 - 4] + 1 = 3;
以此类推
… …
… …
… …
说明:
(0)10 = ( 0)2
(1)10 = ( 1)2
(2)10 = ( 10)2
(3)10 = ( 11)2
(4)10 = (100)2
(5)10 = (101)2
(6)10 = (110)2
(7)10 = (111)2
… …
状态转移公式
count(x + b) = count(x) + 1 其中 b = 2^m > x
3. 代码
#include<iostream>
#include<vector>
using namespace std;
/**
* 题解:https://leetcode-cn.com/problems/counting-bits/solution/bi-te-wei-ji-shu-by-leetcode/
*/
class Solution {
public:
vector<int> countBits(int num) {
// 解空间
vector<int> temp(num + 1);
if(num >= 0) temp[0] = 0;
if(num >= 1) temp[1] = 1;
// count(x + b) = count(x) + 1 其中 b = 2^m > x
int b = 2;
int b2 = 3; // 4 - 1
for(int i = 2; i <= num; i++){
temp[i] = temp[i - b] + 1;
if(i == b2){
b = b2 + 1;
b2 = 2*b2 + 1;
}
}
return temp;
}
};
int main(){
Solution solu;
vector<int> temp = solu.countBits(7);
for(int i = 0; i <= 7; i++){
cout<<temp[i]<<", ";
}
// 输出:0, 1, 1, 2, 1, 2, 2, 3,
return 0;
}
4. 复杂度分析
时间复杂度:O(n)
。对每个整数 x,我们只需要常数时间。
空间复杂度:O(n)
。我们需要 O(n) 的空间来存储技术结果。如果排除这一点,就只需要常数空间。