动态规划解338. Counting Bits

来源:互联网 发布:java分布式开发面试题 编辑:程序博客网 时间:2024/06/09 16:42

题目

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].

题意分析

给定一个数num,求从0到num的数字的二进制中1的个数,比如例子,num=5,则要返回从0到5的数字的二进制中1的个数,0的二进制1的个数为0,1的为1,2的为1,依次类推

思路分析

这是一条动态规划题目,对于一个数是2的n次幂的话,假设为k,那么它二进制1的个数肯定是1,然后之后的数就是g[k+1] = g[k] + g[1], g[k + 2] = g[k] + g[2],g[k+m] = g[k] + g[m]直到某一个数是2的n+1次幂,又重复这个循环,直到要求的数n为止

AC代码

class Solution {public:    vector<int> countBits(int num) {        vector<int> res;        res.push_back(0);        if (num == 0) return res;        res.push_back(1);        int curvalue = 0;        for (int i = 2; i <= num; ++i) {            if ((i & (i-1)) == 0) {                curvalue = i;                res.push_back(1);            } else {                res.push_back(res[curvalue] + res[i - curvalue]);            }        }        return res;    }};
原创粉丝点击