forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdusunax.py
More file actions
42 lines (34 loc) ยท 1.03 KB
/
dusunax.py
File metadata and controls
42 lines (34 loc) ยท 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
'''
# 338. Counting Bits
0๋ถํฐ n๊น์ง์ ์ด์ง์์์ 1์ ๊ฐ์ ์ธ๊ธฐ
## ํ์ดA. ๋ธ๋ฃจํฌํฌ์ค
- ์ ๋ถ ๊ณ์ฐํ๊ธฐ
## ํ์ดB. DP
```
์ด์ง์ = (์ด์ง์ >> 1) + (์ด์ง์ & 1)
```
- `i >> 1`: i์ ๋นํธ๋ฅผ ์ค๋ฅธ์ชฝ์ผ๋ก 1๋นํธ ์ด๋(๋งจ ์ค๋ฅธ์ชฝ ํ ์นธ ๋ฒ๋ฆผ), `i // 2`์ ๊ฐ์
- `i & 1`: `i`์ ๋ง์ง๋ง ๋นํธ๊ฐ 1์ธ์ง ํ์ธ (1์ด๋ฉด 1 ์ถ๊ฐ, 0์ด๋ฉด ํจ์ค)
- DP ํ
์ด๋ธ์์ ์ด์ ๊ณ์ฐ(i >> 1) ๊ฒฐ๊ณผ๋ฅผ ๊ฐ์ ธ์์ ํ์ฌ ๊ณ์ฐ(i & 1) ๊ฒฐ๊ณผ๋ฅผ ๋ํ๋ค.
'''
class Solution:
'''
A. brute force
SC: O(n log n)
TC: O(n)
'''
def countBitsBF(self, n: int) -> List[int]:
result = []
for i in range(n + 1): # TC: O(n)
result.append(bin(i).count('1')) # TC: O(log n)
return result
'''
B. DP
SC: O(n)
TC: O(n)
'''
def countBits(self, n: int) -> List[int]:
dp = [0] * (n + 1)
for i in range(1, n + 1): # TC: O(n)
dp[i] = dp[i >> 1] + (i & 1) # TC: O(1)
return dp