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

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

338. Counting Bits -Medium

2019-11-11 04:28:16
字體:
來源:轉載
供稿:網友

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
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 盘锦市| 惠州市| 成安县| 西乌珠穆沁旗| 新竹市| 论坛| 镇远县| 新和县| 曲周县| 秭归县| 崇信县| 德化县| 灵武市| 日喀则市| 浦城县| 河津市| 绥德县| 垣曲县| 宜川县| 布拖县| 广宁县| 阳原县| 安顺市| 婺源县| 隆德县| 石狮市| 旅游| 兰坪| 清徐县| 鹤岗市| 洛阳市| 郓城县| 盈江县| 塘沽区| 固原市| 无棣县| 禄丰县| 黎川县| 白朗县| 治多县| 太保市|