国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

338. Counting Bits -Medium

2019-11-11 03:58:39
字體:
來源:轉載
供稿:網友

Question

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.

給出一個非負整數num,對[0, num]范圍內的數分別計算它們的二進制數中1的個數,用數組形式返回。

Example

For num = 5 you should return [0,1,1,2,1,2].

Solution

動態規劃解。其實這是道找規律的題目,我們首先列出0-15的數對應的二進制中1的個數

數字 二進制中1的個數 遞推關系式
0 0 dp[0] = 0
1 1 dp[1] = dp[1-1] + 1
2 1 dp[2] = dp[2-2] + 1
3 2 dp[3] = dp[3-2] + 1
4 1 dp[4] = dp[4-4] + 1
5 2 dp[5] = dp[5-4] + 1
6 2 dp[6] = dp[6-4] + 1
7 3 dp[7] = dp[7-4] + 1
8 1 dp[8] = dp[8-8] + 1
9 2 dp[9] = dp[9-8] + 1
10 2 dp[10] = dp[10-8] + 1
11 3 dp[11] = dp[11-8] + 1
12 2 dp[12] = dp[12-8] + 1
13 3 dp[13] = dp[13-8] + 1
14 3 dp[14] = dp[14-8] + 1
15 4 dp[15] = dp[15-8] + 1

綜上,遞推關系式為 dp[n] = dp[n - offset] + 1 (這個規律還真不怎么好找),而offset的更新規律為,每當 offset * 2等于n時,offset就需要更新,即乘以2.

class Solution(object): def countBits(self, num): """ :type num: int :rtype: List[int] """ # 0-num有num + 1個數 dp = [0] * (num + 1) offset = 1 for n in range(1, num + 1): # 根據規律,只要index = 2 * offset,offset需要乘以2 if offset * 2 == n: offset *= 2 # dp[index] = dp[index - offset] + 1 dp[n] = dp[n - offset] + 1 return dp
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 留坝县| 哈巴河县| 大埔县| 穆棱市| 汝阳县| 南昌市| 福清市| 天峻县| 连云港市| 海南省| 方城县| 临沂市| 大英县| 黄浦区| 海林市| 和平区| 淮北市| 八宿县| 榆树市| 石台县| 蒲江县| 巢湖市| 武强县| 林芝县| 阿荣旗| 定南县| 洛浦县| 山阴县| 柳州市| 西吉县| 江孜县| 武宣县| 恩施市| 高州市| 南通市| 扬中市| 若尔盖县| 舟曲县| 遂川县| 石渠县| 江安县|