338. LeetCode_DP_Counting Bits

来源:互联网 发布:蒙特卡洛算法 matlab 编辑:程序博客网 时间:2024/05/16 07:39

一、题目

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.

Hint:

  1. You should make use of what you have produced already.
  2. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous.
  3. Or does the odd/even status of the number help you in calculating the number of 1s?
二、解题思路

题目意思是找出0到输入数字之中,每个数字的二进制表示所含1的数目。
例如5,从0到5,发现每个后一个数字都依赖于前面的某个数字的结果,通过二进制计算方式发现了规律;
比如0,被2除后,余数为0;结果是0; (0个1)
第一步,1被2除后,结果是0;余数是1;(未能整除)   
              再用得到的结果0,被2除,结果是0,而0为初始的结果;
      所以就是初始的结果(0)+1=1(1的二进制表示共有1个1)。
第二步,2被2除后,结果是1;余数是0;(能整除) 
     再用得到的结果1,被2除,发现第一步已经计算过了;
      所以就是第一步的结果(1)(2的二进制表示共有1个1)
第三步,3被2除后,结果是1;余数是1;(未能整除)
             再用得到的结果1,被2除,发现第一步已经计算过了;
             所以就是第一步的结果(1)+1=2(3的二进制表示共有2个1)
第四步,4被2除后,结果是2;余数是2;(能整除)
             再用得到的结果2,被2除,发现第二步已经计算过了;
             所以就是第二步的结果(1)(4的二进制表示共有1个1)
第五步,5被2除后,结果是2;余数是1;(未能整除)
             再用得到的结果1,被2除,发现第二步已经计算过了;
             所以就是第二步的结果(1)+1=2 (5的二进制表示共有2个1)

所以结果就是[0,1,1,2,1,2]

三、Java代码

public class Solution {    public int[] countBits(int num)     {        int[] dp = new int[num+1];        dp[0] = 0;                for (int i=1; i<=num; i++)         {            if(i % 2 == 0)                dp[i] = dp[i / 2];            else                dp[i] = dp[i / 2] + 1;         }        return dp;    }}









0 0
原创粉丝点击