欢迎来到PJCK的博客

(DP 线性DP) leetcode 338. 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 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.

===========================================

参考链接:https://leetcode-cn.com/problems/counting-bits/solution/338-bi-te-wei-ji-shu-javati-jie-dong-tai-gui-hua-b/

这个大佬已经解释清楚了,找找规律就行。

 /**
     * 题目已经强调了需要O(n)的复杂度,只能遍历一遍,可以考虑动态规划
     * 根据题目意思,先手动画一下数字和2进制的具体映射关系
     * 数字   0    1   2   3   4   5   6   7   8
     * 二进   0    1   10  11  100 101 110 111 1000
     * 1个数  0   1   1   2   1   2   2   3   1
     * 根据递推效果,看着好像没有什么规律
     * 但是仔细思考下,10进制转2进制必须要除以2,有些能整除,有些不能整除
     * 不能整除的3的1个数=3/1=数字1的1个数+1
     * 能整除的4的的1个数=4/2=数字2的1个数
     * 拿其他数字验证后发现的确是这个规律,得到动态规划状态转移方程:
     * int d = i / 2;
     * int m = i % 2;
     * if (m == 0) {
     *  dp[i] = dp[d];
     * } else {
     *  dp[i] = dp[d] + 1;
     * }
     *
     * @param num
     * @return
     */

 

C++代码:

class Solution {
public:
    vector<int> countBits(int num) {
        vector<int> dp(num+1,0);
        for(int i = 1; i <= num; i++){
            int d = i / 2;
            int m = i % 2;
            if(m == 0)
                dp[i] = dp[d];
            else
                dp[i] = dp[d] + 1;
        }
        return dp;
    }
};

 

posted @ 2019-05-14 22:33  PJCK  阅读(132)  评论(0编辑  收藏  举报