Skip to content

[wozlsla] WEEK 03 solutions #1802

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 10, 2025
Merged
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
34 changes: 34 additions & 0 deletions combination-sum/wozlsla.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"""
# Intuition
중복을 허용하는 조합?

# Approach
- X
"""


class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

candidates.sort()를 함수 시작 부분에 추가하면 불필요한 탐색을 줄일 수 있음

result, nums = [], []

def dfs(start, total):

# 기저조건 1
if total > target:
return

# 기저조건 2
if total == target: # sum to target 찾음
result.append(nums[:]) # 복사본 추가
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nums[:] 복사 대신 list(nums)도 동일한 효과를 내며 가독성이 조금 좋아질 것 같습니다


for i in range(start, len(candidates)):
num = candidates[i]
nums.append(num)
dfs(i, total + num)
nums.pop()

# 재귀함수 호출
dfs(0, 0)

return result
19 changes: 19 additions & 0 deletions maximum-subarray/wozlsla.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
"""
# Intuition
- X
# Approach
- X
"""


class Solution:
def maxSubArray(self, nums: List[int]) -> int:

max_total = nums[0]

for i in range(len(nums)): # O(N)
for j in range(i, len(nums)): # O(N)

max_total = max(sum(nums[i : j + 1]), max_total) # O(N)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sum()이 매번 새로 계산돼서 비효율적일 것 같습니다


return max_total
48 changes: 48 additions & 0 deletions number-of-1-bits/wozlsla.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
"""
# Intuition
이진수로 변환 후 1 세기

# Approach
n % 2 (나머지)가 1이면 cnt += 1

# Complexity
- Time complexity : O(logN)
- 10진수 n을 2진수로 변환했을 때 비트의 개수는 log2(n)에 비례. 따라서 이 루프는 약 log2(n)번 반복
- Space complexity : O(N)
- bin(n) 함수는 n의 2진수 표현을 담는 새로운 문자열을 생성. 이 문자열의 길이는 logn에 비례 : O(logN)
"""


class Solution:
def hammingWeight(self, n: int) -> int:

cnt = 0

while n > 0:
cnt += n % 2
n //= 2

# if n % 2 == 1:
# cnt += 1
# n = n // 2

return cnt


"""
class Solution:
def hammingWeight(self, n: int) -> int:

# return bin(n).count("1")

cnt = 0

for b in bin(n):
if b == 1:
cnt += 1

return cnt
"""

sol = Solution()
print(sol.hammingWeight(11))
128 changes: 128 additions & 0 deletions valid-palindrome/wozlsla.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
"""
# Intuition
소문자 변환, 영숫자 제외한 문자 제거
reverse와 비교

# Approach
1. non-alphanumeric(isalpha/isnum or 정규식) 일 때
2. lower()
3. 위 객체를 비교

- chars = "" 와 같이
빈 문자열을 만들고 반복문을 돌며 chars += char 형태로 문자를 하나씩 추가하면, 매번 새로운 문자열 객체를 생성하기 때문에 성능 비용이 큼.
-> 리스트에 하나씩 추가한 뒤, 마지막에 "".join() 메서드 사용

# Complexity
- Time complexity : O(N)
- Space complexity : O(N)
"""


class Solution:
def isPalindrome(self, s: str) -> bool:

chars = []

for char in s:
if char.isalnum():
chars.append(char.lower())

result = "".join(chars)

# list comprehension
# chars = "".join([char.lower() for char in s if char.isalnum()])

return result == result[::-1]


sol = Solution()
s = "A man, a plan, a canal: Panama"

print(sol.isPalindrome(s))


# Pointer : O(1)
class Solution:
def isPalindrome(self, s: str) -> bool:

left, right = 0, len(s) - 1

while left < right:

if not s[left].isalnum():
left += 1
continue
if not s[right].isalnum():
right -= 1
continue

# while left < right and not s[left].isalnum():
# left += 1
# while left < right and not s[right].isalnum():
# left -= 1

if s[left].lower() != s[right].lower():
return False

left += 1
right -= 1

return True


""" 전처리 필요함
class Solution:
def isPalindrome(self, s: str) -> bool:

chars = re.sub(r'[^a-zA-Z0-9]', '', s).lower()

for i in range(len(chars)//2):
left = chars[i]
right = chars[len(chars) - 1 - i]

if left != right:
return False

return True
"""

""" 정규식
import re

class Solution:
def isPalindrome(self, s: str) -> bool:

chars = re.sub(r'[^a-zA-Z0-9]', '', s).lower()

return chars == chars[::-1]
"""

"""
# non-alphanumeric
- isalpha()
- 문자열이 모두 알파벳(영문)으로만 구성되어 있는지 확인
- 한글, 일본어 등 다른 언어의 문자도 포함 ('안녕하세요'.isalpha() → True)
- 공백, 숫자, 특수문자 포함 X
- isnumeric()
- 문자열이 모두 숫자로만 구성되어 있는지 확인
- 숫자는 단순히 아라비아 숫자(0-9)뿐만 아니라, 유니코드 숫자(예: ①, ², 한자 숫자)도 포함 ('①②③'.isnumeric() → True)
- 소수점(.)이나 음수 부호(-)는 숫자로 간주하지 X
- isalnum()
- isalpha()와 isnumeric()의 조건을 합친 것으로, 문자열이 모두 알파벳 또는 숫자로 구성되어 있는지 확인

# 객체 역순
- .reverse()
- list 객체에만 사용
- 원본 수정, 반환값 None
- reversed()
- 리스트, 튜플, 문자열 등 모든 iterable 객체에 사용 가능
- 새로운 역순 'iterator' 객체를 반환, 원본 객체 변경 X
- 반환된 이터레이터는 리스트나 튜플 등으로 변환하여 사용해야 함. 메모리 효율이 중요한 경우 유용
- 슬라이싱 [::-1]
- 리스트, 튜플, 문자열 등 모든 iterable 객체에 사용 가능
- 원본을 복사하여 역순으로 정렬된 새로운 객체를 반환, 원본 객체 변경 X
- 원본 전체를 복사하므로 메모리 사용량이 reversed() 보다 더 많을 수 있다

* iterator
데이터의 순차적인 접근 방식을 정의하는 객체일 뿐, 그 자체로 모든 데이터를 메모리에 담고 있는 리스트나 튜플과 같은 직접적인 데이터 구조가 아니다.
"""