File tree 1 file changed +44
-2
lines changed
1 file changed +44
-2
lines changed Original file line number Diff line number Diff line change @@ -1316,12 +1316,11 @@ class Solution(object):
1316
1316
return res[amount]
1317
1317
```
1318
1318
1319
-
1320
1319
## 338. 比特位计数
1321
1320
1322
1321
[ 原题链接] ( https://leetcode-cn.com/problems/counting-bits/description/ )
1323
1322
1324
- ### 思路
1323
+ ### 解法一
1325
1324
1326
1325
动态规划无疑了
1327
1326
@@ -1349,6 +1348,49 @@ class Solution(object):
1349
1348
return List1[:num+ 1 ]
1350
1349
```
1351
1350
1351
+ ### 解法二
1352
+
1353
+ 奇偶数的二进制规律:
1354
+
1355
+ - 奇数二进制数总比前一个偶数二进制数多 1 个 1(即最后 1 位)
1356
+ - 偶数二进制数 ` x ` 中 1 的个数总等于 ` x / 2 ` 中 1 的个数(除 2 等于右移 1 位,即抹去最后一位 0)
1357
+
1358
+ <!-- tabs:start -->
1359
+
1360
+ c
1361
+
1362
+ ``` python
1363
+ class Solution :
1364
+ def countBits (self , num : int ) -> List[int ]:
1365
+ ans = [0 for _ in range (num + 1 )]
1366
+ for i in range (num + 1 ):
1367
+ if i % 2 == 0 :
1368
+ # 偶数
1369
+ ans[i] = ans[i // 2 ]
1370
+ else :
1371
+ # 奇数
1372
+ ans[i] = ans[i - 1 ] + 1
1373
+ return ans
1374
+ ```
1375
+
1376
+ #### ** Go**
1377
+
1378
+ ``` go
1379
+ func countBits (num int ) []int {
1380
+ ans := make ([]int , num + 1 )
1381
+ for i := 0 ; i <= num; i++ {
1382
+ if i % 2 == 0 {
1383
+ ans[i] = ans[i / 2 ]
1384
+ } else {
1385
+ ans[i] = ans[i - 1 ] + 1
1386
+ }
1387
+ }
1388
+ return ans
1389
+ }
1390
+ ```
1391
+
1392
+ <!-- tabs:end -->
1393
+
1352
1394
## 714. 买卖股票的最佳时机含手续费
1353
1395
1354
1396
[ 原题链接] ( https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/ )
You can’t perform that action at this time.
0 commit comments