Skip to content

Commit 531a2c3

Browse files
authored
Merge pull request #2093 from socow/main
[socow] WEEK 03 solutions
2 parents 84f4816 + faf6d98 commit 531a2c3

File tree

3 files changed

+68
-0
lines changed

3 files changed

+68
-0
lines changed

β€Žcombination-sum/socow.pyβ€Ž

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
"""
2+
문제 μš”μ•½
3+
- candidates λ°°μ—΄μ—μ„œ 숫자λ₯Ό λ¬΄μ œν•œ μ‚¬μš©ν•˜μ—¬ 합이 target이 λ˜λŠ” λͺ¨λ“  μ‘°ν•© μ°ΎκΈ°
4+
5+
아이디어
6+
- λ°±νŠΈλž˜ν‚Ή: i번째 μΈλ±μŠ€λΆ€ν„° νƒμƒ‰ν•˜μ—¬ 쀑볡 μ‘°ν•© λ°©μ§€
7+
- 같은 숫자 μž¬μ‚¬μš© κ°€λŠ₯ β†’ μž¬κ·€ μ‹œ 인덱슀 i μœ μ§€
8+
- μ •λ ¬ ν›„ target 초과 μ‹œ break둜 κ°€μ§€μΉ˜κΈ°
9+
10+
μ‹œκ°„λ³΅μž‘λ„: O(N^(T/M)) - N: candidates 길이, T: target, M: μ΅œμ†Œκ°’
11+
κ³΅κ°„λ³΅μž‘λ„: O(T/M) - μž¬κ·€ 깊이
12+
"""
13+
14+
class Solution:
15+
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
16+
result = []
17+
sol = []
18+
candidates.sort()
19+
n = len(candidates)
20+
21+
def backtrack(start, cur_sum):
22+
if cur_sum == target:
23+
result.append(sol.copy())
24+
return
25+
26+
for i in range(start, n):
27+
if cur_sum + candidates[i] > target:
28+
break
29+
sol.append(candidates[i])
30+
backtrack(i, cur_sum + candidates[i])
31+
sol.pop()
32+
33+
backtrack(0, 0)
34+
return result

β€Žnumber-of-1-bits/socow.pyβ€Ž

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
"""
2+
문제 μš”μ•½
3+
- 32λΉ„νŠΈ λΆ€ν˜Έ μ—†λŠ” μ •μˆ˜ n의 이진 ν‘œν˜„μ—μ„œ '1'의 개수(= set bits)λ₯Ό κ΅¬ν•˜λΌ.
4+
5+
아이디어 A: λΈŒλΌμ΄μ–Έ μ»€λ‹ˆν•Έ(Brian Kernighan) μ•Œκ³ λ¦¬μ¦˜
6+
- 핡심 κ΄€μ°°: n & (n - 1)은 n의 μ΅œν•˜μœ„ 1λΉ„νŠΈλ₯Ό '0'으둜 λ§Œλ“ λ‹€.
7+
예) n = 0b101100 β†’ n-1 = 0b101011 β†’ n & (n-1) = 0b101000 (μ΅œν•˜μœ„ 1 ν•˜λ‚˜ μ‚­μ œ)
8+
- λ”°λΌμ„œ '1'의 개수만큼 루프가 λˆλ‹€.
9+
- μ‹œκ°„λ³΅μž‘λ„: O(k) (k = n의 1λΉ„νŠΈ 개수) ← 맀우 빠름
10+
- κ³΅κ°„λ³΅μž‘λ„: O(1)
11+
"""
12+
13+
class Solution:
14+
def hammingWeight(self, n: int) -> int:
15+
cnt = 0
16+
while n:
17+
n &= n - 1 # μ΅œν•˜μœ„ 1λΉ„νŠΈ 제거
18+
cnt += 1
19+
return cnt

β€Žvalid-palindrome/socow.pyβ€Ž

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
"""
2+
문제 μš”μ•½
3+
- 영숫자만 κ³ λ €, λŒ€μ†Œλ¬Έμž λ¬΄μ‹œ β†’ νŒ°λ¦°λ“œλ‘¬ μ—¬λΆ€
4+
5+
아이디어
6+
- μ†Œλ¬Έμž λ³€ν™˜ β†’ 영숫자만 ν•„ν„° β†’ μ—­μˆœκ³Ό λ™μΌν•œμ§€ 비ꡐ
7+
8+
μ‹œκ°„λ³΅μž‘λ„: O(n)
9+
κ³΅κ°„λ³΅μž‘λ„: O(n)
10+
"""
11+
12+
class Solution:
13+
def isPalindrome(self, s: str) -> bool:
14+
cleaned = [c for c in s.lower() if c.isalnum()]
15+
return cleaned == cleaned[::-1]

0 commit comments

Comments
Β (0)