日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

338. Counting Bits(动态规划)

發布時間:2024/4/14 52 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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:
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;} };

轉載于:https://www.cnblogs.com/A-Little-Nut/p/8323535.html

總結

以上是生活随笔為你收集整理的338. Counting Bits(动态规划)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。