[338] leetcode count bits (dynamic programming bit operation)

Topic links: https://leetcode-cn.com/problems/counting-bits/

Title Description

Given a non-negative integer num. For 0 ≤ i ≤ i, each digital num range, which calculates the number of binary digits 1 and returns them as an array.

Example 1:

输入: 2
输出: [0,1,1]
示例 2:

输入: 5
输出: [0,1,1,2,1,2]

Advanced:

  • The time complexity is given O(n*sizeof(integer))the answer is easy. But you can in linear time O(n)with one pass do it inside?
  • Requirements algorithm space complexity O(n).
  • You can further improve the solution it? Request does not use any built-in functions (e.g., in __builtin_popcount C ++) in C ++ or any other language to do this.

Thinking

1 violence

Complexity Analysis
time complexity: O (n * sizeof (int ))
spatial complexity: O (n)

class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> ret = {0};
        for(int i = 1; i< num+1; ++i){
            int cnt = 0;
            unsigned bit = 0x01;
            for (int j = 0;j<32;++j){
                cnt += ((bit & i) !=0);
                bit = bit <<1;
            }
            ret.push_back(cnt);
        }
        return ret;
    }
};

Here Insert Picture Description

2 optimized violence

Can be observed:

n = n&(n-1)

N corresponds to the rightmost 1 is set to 0, and n is 0 can be obtained after several operation indicates the number of bits n 1. There are several integer 1 only needs to loop a few times.

class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> ret = {0};
        for(int i = 1; i< num+1; ++i){
            int cnt = 0;
            int n = i;
            while(n!=0){
                ++ cnt;
                n = (n-1) & n;
            }
            ret.push_back(cnt);
        }
        return ret;
    }
};

Here Insert Picture Description
Complexity Analysis
time complexity: O (n * k)
Complexity Space: O (n-)
K is the average number of bits 1

3 Dynamic Programming

Dynamic programming equation:
If iis odd: dp[i] = dp[i-1] + 1
if ian even number:dp[i] = dp[i>>1]

Complexity Analysis
time complexity: O (n)
complexity of space: O (n)

/*
 * 动态规划
 * 时间复杂度O(n) 空间复杂度O(n)
 */
class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> ret = {0};
        for(int i = 1; i< num+1; ++i){
            if (i & 0x01)
                ret.push_back(ret[i>>1]+1); // 或者ret[i-1]+1
            else
                ret.push_back(ret[i>>1]);
        }
        return ret;
    }
};

Guess you like

Origin blog.csdn.net/zjwreal/article/details/91491183