leetcode338 Counting Bits

题目:

  

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:
For num = 5 you should return [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

看到大部分解法都是根据二进制直接推的,我做的时候因为当时在学习dp相关,所以一下子 直接按dp来做的,相当于2的n-1次到2的n次做递归循环,状态转移方程比较容易做出来,不过感觉还是直接二进制来做更符合这道题的本质。下面是我的代码:

public class Solution {
    public int[] countBits(int num) {
    int[] a = new int[num+1];
    int y =0;
    if(num == 0){
        a[0] = 0;
    }else if(num == 1){
        a[0] = 0;
        a[1] = 1;
    }else{
        a[0] = 0;
        a[1] = 1;
        int T = 2;
          for(int i =2;i <= num;i++){
            
            if(i == T){
               T = T * 2;
               y = 0;
            }
            a[i] = a[y] + 1;
            y++;
        }
    }
    return a;
    }
}
原文地址:https://www.cnblogs.com/feary/p/5382750.html