LeetCode刷题: 【338】比特位计数(动态规划)

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) 的空间来存储技术结果。如果排除这一点,就只需要常数空间。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值