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) 的空間來存儲技術結果。如果排除這一點,就只需要常數空間。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章