Likou 338. Bit count bit operation dp

https://leetcode-cn.com/problems/counting-bits/
Insert picture description here
Idea 1: A number can be expressed by the sum of powers of 2, then suppose the current increase is add adda d d , by enumerating all greater thanadd adda d d and less than or equal tonum numThe power of 2 of n u m can recursively deduce a new number.

class Solution {
    
    
public:
    vector<int> countBits(int num) {
    
    
        vector<int> ans(num+1);
        int cur=1,add=0;
        while(cur+add<=num)
        {
    
    
            if(add==cur)
                cur<<=1;
            int tmpcur=cur;
            while(tmpcur+add<=num)
            {
    
    
                if(add)
                    ans[tmpcur+add]=ans[tmpcur]+ans[add];
                else
                    ans[tmpcur]=1;
                tmpcur<<=1;
            }
            ++add;
        }
        return ans;
    }
};

Idea 2: Recursion (dp).

class Solution {
    
    
public:
    vector<int> countBits(int num) {
    
    
        vector<int> ans(num+1);
        for(int i=1;i<=num;i++)
            ans[i]=ans[i>>1]+(i&1);
        return ans;
    }
};

Guess you like

Origin blog.csdn.net/xiji333/article/details/114332775
Recommended