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.

分析:

这道题完全没看别人的思路,自己想出来的第一道动态规划题目,开心<( ̄︶ ̄)>
当n为奇数时,则n-1为偶数,由二进制可知,n-1的二进制最后一位必定是0
而n的二进制就是在n-1的二进制最后一位加1,并未影响n-1的前面的情况,只把最后一位0,变为了1,所以当n=奇数时,dp[n]=dp[n-1]+1;
举个栗子:6=1*(2^2)+1*(2^1)+0*(2^0),6的二进制是110.
7=1*(2^2)+1*(2^1)+1*(2^0),7的二进制是111.
当n为偶数时,先举个栗子吧,
6=1*(2^2)+1*(2^1)+0*(2^0),6的二进制是110.
n/2就是把每一项都除以2,但是你会发现每一项的系数是不变的,
6/2=3=1*(2^1)+1*(2^0)+0(2^0)
所以当n=偶数时,dp[n]=dp[n/2].
class Solution {
public:
vector<int> countBits(int num) {
vector<int> dp(num+1,0);
for(int i=1;i<num+1;i++){
if(i%2==0)
dp[i]=dp[i/2];
else
dp[i]=dp[i-1]+1;
}
return dp;
}
};

最新文章

  1. tail -f 和 -F 的用法
  2. 服务器唯一id生成规则
  3. gridview 字段没有绑定由于column visible= false
  4. Re-installation failed due to different application signatures.
  5. TFS二次开发、C#知识点、SQL知识
  6. ADO.NET中SQL Server数据库连接池
  7. Map Task内部实现分析
  8. npm ERR! Refusing to install package with name &quot;webpack&quot; under a package -----
  9. JS json字符串转对象、对象转字符串
  10. 启动PHP study时提示80端口或者3306端口被占用的解决办法
  11. Hibernate映射数据库中longtext类型属性时报错No Dialect mapping for JDBC type: -1的解决方案
  12. django之用户表的继承
  13. 如何在Android平台上使用USB Audio设备
  14. 终端控制类getopt isatty select ttyname
  15. visualstudio 2013 mysql entityframework :实体模型无法添加,闪退
  16. Volley框架实现Http的get和post请求
  17. iOS 真机调试多台mac电脑共用一个证书
  18. bootstrap-datetimepicker 开始时间与结束时间互相约束
  19. 第一百九十六节,jQuery EasyUI,Tooltip(提示框)组件
  20. Unexpected exception parsing XML document from ServletContext resource [/WEB-INF/config/springdemo-config.xml]

热门文章

  1. 继承自TWinControl的控件不能在设计期间接受子控件,用代码设置子控件却可以(它的自绘是直接改写PaintWindow虚函数,而不是覆盖Paint函数——对TWinControl.WMPaint又有新解了)
  2. Java 并发编程(二)对象的公布逸出和线程封闭
  3. Linux下的IPC-UNIX Domain Socket【转】
  4. 【Poj1325】Machine Schedule机器调度
  5. HDU3487 Play with Chain splay 区间反转
  6. 如何判断js的变量的数据类型
  7. [App Store Connect帮助]一、 App Store Connect 使用入门(4)iOS 版 App Store Connect
  8. 数据库部署到linux服务器,供本地访问。
  9. BZOJ 3798 分块打表
  10. Java保存错误日志信息