338. Counting Bits(动态规划)
生活随笔
收集整理的這篇文章主要介紹了
338. Counting Bits(动态规划)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
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.
分析:
這道題完全沒(méi)看別人的思路,自己想出來(lái)的第一道動(dòng)態(tài)規(guī)劃題目,開(kāi)心<( ̄︶ ̄)> 當(dāng)n為奇數(shù)時(shí),則n-1為偶數(shù),由二進(jìn)制可知,n-1的二進(jìn)制最后一位必定是0 而n的二進(jìn)制就是在n-1的二進(jìn)制最后一位加1,并未影響n-1的前面的情況,只把最后一位0,變?yōu)榱?,所以當(dāng)n=奇數(shù)時(shí),dp[n]=dp[n-1]+1; 舉個(gè)栗子:6=1*(2^2)+1*(2^1)+0*(2^0),6的二進(jìn)制是110.7=1*(2^2)+1*(2^1)+1*(2^0),7的二進(jìn)制是111. 當(dāng)n為偶數(shù)時(shí),先舉個(gè)栗子吧,6=1*(2^2)+1*(2^1)+0*(2^0),6的二進(jìn)制是110. n/2就是把每一項(xiàng)都除以2,但是你會(huì)發(fā)現(xiàn)每一項(xiàng)的系數(shù)是不變的,6/2=3=1*(2^1)+1*(2^0)+0(2^0) 所以當(dāng)n=偶數(shù)時(shí),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;} };轉(zhuǎn)載于:https://www.cnblogs.com/A-Little-Nut/p/8323535.html
總結(jié)
以上是生活随笔為你收集整理的338. Counting Bits(动态规划)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: C# 编码约定(C# 编程指南)
- 下一篇: Java 集合框架部分面试题