leetcode014-Counting Bits

来源:互联网 发布:中科汇通知乎 编辑:程序博客网 时间:2024/06/09 14:36

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[i]代表数字i的二进制含有多少个1
  如果i是奇数的话,i-1是偶数,那个i-1的二进制的最低位一定是0,加1并不会进位,所以dp[i] = dp[i-1]+1
  如果i是偶数的话,i会与i/2的二进制拥有相同个数的1,因为i/2左移一位,最后补0,就是i,所以dp[i] = dp[i/2]
class Solution {public:    vector<int> countBits(int num) {        vector<int> dp(num+1,0);        for (int i = 1; i <= num; i++) {            if (i%2==0) {                dp[i] = dp[i/2];            } else {                dp[i] = dp[i-1]+1;            }        }        return dp;    }};


原创粉丝点击