Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions combination-sum/riveroverflows.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
class Solution:
"""
TC: O(N^(T/M))
- N = len(candidates), T = target, M = min(candidates)
SC: O((T/M) * N^(T/M))

풀이:
백트래킹으로 모든 조합을 탐색하되, 중복 조합 방지를 위해
start 인덱스를 활용하여 이전 후보는 건너뛰고, 같은 후보는 재사용 허용.
path_sum > target이면 가지치기(pruning)하여 불필요한 탐색을 줄임.
"""
def combinationSum(self, candidates: list[int], target: int) -> list[list[int]]:
answer = []

def backtrack(start, path, path_sum):
if path_sum > target:
return

if path_sum == target:
answer.append(path[:])
return

for i in range(start, len(candidates)):
candidate = candidates[i]
path.append(candidate)
path_sum += candidate
backtrack(i, path, path_sum)
path_sum -= candidate
path.pop()

backtrack(0, [], 0)

return answer
20 changes: 20 additions & 0 deletions number-of-1-bits/riveroverflows.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from typing import *


class Solution:
"""
TC: O(log n)
SC: O(1)

풀이:
Brian Kernighan의 비트 트릭을 활용.
n & (n-1)은 n의 가장 오른쪽 1비트를 하나 제거한다.
n이 0이 될 때까지 반복한 횟수가 곧 1비트의 개수.
"""
def hammingWeight(self, n: int) -> int:
answer = 0
while n > 0:
n = n & (n - 1)
answer += 1

return answer
36 changes: 36 additions & 0 deletions valid-palindrome/riveroverflows.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
class Solution:
"""
풀이 1: 투포인터
TC: O(n)
SC: O(1)

양쪽 끝에서 포인터를 좁혀가며 알파벳/숫자만 비교.
"""
def isPalindrome(self, s: str) -> bool:
l, r = 0, len(s) - 1
while l < r:
if not s[l].isalnum():
l += 1
continue
if not s[r].isalnum():
r -= 1
continue

if s[l].lower() != s[r].lower():
return False

l += 1
r -= 1

return True

"""
풀이 2: 리스트 변환 + 역순 비교
TC: O(n)
SC: O(n)

알파벳/숫자만 추출한 리스트를 역순과 비교.
"""
def isPalindrome2(self, s: str) -> bool:
s = [c for c in s.lower() if c.isalnum()]
return s == s[::-1]
Loading