Skip to content
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
21 changes: 21 additions & 0 deletions combination-sum/Donghae0230.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# 문제 풀이
# 모든 경우의 수를 탐색하기 위해 백트래킹 사용
# - 현재 조합의 합이 target보다 크면 종료
# - 현재 조합의 합이 target과 같으면 결과에 추가

class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
def backtrack(start, combination):
if sum(combination) > target:
return
if sum(combination) == target:
result.append(combination[:])
return
for i in range(start, len(candidates)):
combination.append(candidates[i])
backtrack(i, combination)
Copy link
Contributor

Choose a reason for hiding this comment

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

가독성 좋은 백트래킹 풀이인 것 같습니다!

여기에 추가로 candidates를 정렬한다면 pruning을 적용할 수 있어 더 최적화 된 풀이가 가능할 것 같아요~!

combination.pop()

result = []
backtrack(0, [])
return result
21 changes: 21 additions & 0 deletions number-of-1-bits/Donghae0230.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# 문제 풀이
# 1. 입력값 n을 binary 형태로 변환
# - 입력값 n이 1보다 크면 2로 나눠 몫과 나머지 계산
# - 나머지를 리스트에 추가해 반환
# 2. 반환된 리스트에서 1의 갯수 반환

# 시간복잡도 O(log n): n을 2로 나누면서 재귀 함수 실행
# 공간복잡도 O(log n): 비트를 저장하는 리스트의 길이

class Solution:
def devide_by_2 (self, n, temp):
if n > 1 :
temp.append(n % 2)
return self.devide_by_2(n // 2, temp)
Copy link
Contributor

Choose a reason for hiding this comment

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

n & n-1로 오른쪽에서부터 1인 비트를 하나씩 지워가며 개수를 세는 방식인 Brian Kernighan's 알고리즘이라는 방법도 있어 공유드립니다~!

https://leetcode.com/problems/number-of-1-bits/solutions/4341511/faster-lesser-3-methods-simple-count-brian-kernighan-s-algorithm-bit-manipulation-explained

temp.append(1)
return n, temp

def hammingWeight(self, n: int) -> int:
result = []
n, result = self.devide_by_2(n, result)
return result.count(1)
16 changes: 16 additions & 0 deletions valid-palindrome/Donghae0230.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# 문제 풀이
# 1. 문자열을 소문자로 변환 후 문자와 숫자가 아닌 값을 제거
# 2. 문자열을 뒤집은 후 원래 문자열과 비교

# 시간복잡도 O(n): 문자열 처리(re.sub, reversed 등) 사용
# 공간복잡도 O(n): 원래 문자열 만큼의 공간 사용
import re

class Solution:
def isPalindrome(self, s: str) -> bool:
cleaned_s = re.sub(r'[^a-zA-Z0-9]', '', s.lower())
reversed_s = ''.join(reversed(cleaned_s))
if cleaned_s == reversed_s:
return True
else:
return False