动态规划解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; }};
阅读全文
0 0
- 动态规划解338. Counting Bits
- leetcode -- 338. Counting Bits 【动态规划】
- 338. Counting Bits(动态规划)
- 动态规划——338. Counting Bits[Medium]
- 【动态规划】Leetcode编程题解:338. Counting Bits
- [leetcode] 338. Counting Bits
- 338. Counting Bits
- leetcode 338. Counting Bits
- LeetCodeOJ:338. Counting Bits
- [LeetCode]338. Counting Bits
- LeetCode#338. Counting Bits
- 338. Counting Bits
- [LeetCode] 338. Counting Bits
- LeetCode 338. Counting Bits
- 338. Counting Bits
- [LeetCode]338. Counting Bits
- LeetCode-338. Counting Bits
- LeetCode *** 338. Counting Bits
- Linux开发环境搭建与使用——arm开发板连接终端( xshell )
- NBUT
- HDU2053Switch Game
- 2017 ICPC 区域赛小记
- 反射笔记二
- 动态规划解338. Counting Bits
- linux下创建eclipse快捷方式
- 菜鸟学java----非静态内部类
- OK6410DRAM存储器的初始化
- ACdream
- Visual Page Editor has experimental support for Windows 64-bit
- 利用七牛云解决PC端文件同步
- Java 深入学习(12) —— 装箱与拆箱
- Docky wiki