338. Counting Bits(DP)

Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.

Example 1:

Input: 2
Output: [0,1,1]

Example 2:

Input: 5
Output: [0,1,1,2,1,2]

Follow up:

  • It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
  • Space complexity should be O(n).
  • Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.

由于计算机组成原理的思想没有深入骨髓,因此对二进制的理解还是不够透彻,只能想到最简单粗暴的方法,下面先附上我自己的代码然后着重解释大佬的方案吧。

class Solution {
public:
    vector countBits(int num) {
        vector arr(num+1,0);
        for(int i=0;i<=num;i++){
            int j=i;
            while(j!=0){
                if(j%2 == 1){
                    arr[i]++;  
                }
                j /= 2;
            }
        }
        return arr;
    }
};

DP方案:

class Solution {
public:
    vector countBits(int num) {
        vector ret(num+1, 0);
        for (int i = 1; i <= num; ++i)
            ret[i] = ret[i&(i-1)] + 1;
        return ret;
    }
};

解释:举例i=14,二进制表示为1110,i-1的二进制为1101,那么i&(i-1)为1100,有一个1被抵消了,所以状态转移方程为:

           dp[i]=dp[i&(i-1)]+1 

           dp[0]=0

你可能感兴趣的:(算法)