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
40 changes: 40 additions & 0 deletions combination-sum/liza0525.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
class Solution:
# DFS로 문제를 푼다. 단, 가지치기 필요.
# 이 때 가지치기를 하기 위해 candidates을 먼저 오름차순으로 sorting을 하고 (각 요소는 unique한 숫자)
# 실제 target 숫자와 지금까지 저장해돈 target_list의 합의 대소 비교를 하며 깊이 탐색을 더 할지 말지 결정한다.
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
results = []

# candidates를 먼저 sorting(문제 조건에 sort가 되어 있다는 점이 없음)
candidates.sort()
len_candidates = len(candidates)

# 깊이 우선 탐색 함수
def dfs(target_list, start_i):
for i in range(start_i, len_candidates):
if sum(target_list) == target:
# target_list를 results에 넣어준다.
# target_list는 리스트 객체이므로 deepcopy를 해서 넣어줘야 함
# 이 이상 탐색해봤자 target보다 큰 값이 나오기 때문에 탐색을 마친다.
results.append(target_list[:])
return

if sum(target_list) + candidates[i] > target:
# 지금까지 쌓아온 target_list의 전체 합과 현재 인덱스의 값을 더한 것이
# target보다 크면 더이상 탐색하지 않아도 된다(뒤에 있는 index의 값도 다 무조건 커짐)
# 따라서 탐색을 마치기 위해 return한다.
return

# 탐색을 계속해야 하는 경우에는 target_list에 candidate[i]의 값을 넣어준 후
# 그 다음 깊이 탐색을 한다.
# i번째 수보다 작은 수를 탐색할 필요가 없기 때문에 다음 탐색의 start_i로 현 시점의 i를 넣어준다.
target_list.append(candidates[i])
dfs(target_list, i)

# 탐색을 끝내고 오면 pop
target_list.pop()

# 깊이 우선 탐색 시작
dfs([], 0)

return results
22 changes: 22 additions & 0 deletions number-of-1-bits/liza0525.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# 시간 복잡도: O(log n)
# - 2로 계속 나누고, 이는 2진수 자릿수 만큼 반복하기 때문
# 공간 복잡도: O(1)
# - 변수 몇 개만 사용

class Solution:
# 어떤 수를 2진수로 변환하는 과정은 2로 나눈 후, 그 나머지(1 또는 0)을 가장 높은 자리 수부터 순차로 나열하고
# 몫을 그 다음 회차의 피제수로 사용하면 된다.
# 해당 문제는 나열하지 않고 대상 수를 2로 나눌 때 매 회차의 나머지를 더해줌으로써 풀 수 있다.
def hammingWeight(self, n: int) -> int:
bits_sum = 0
while n >= 1:
# 모듈로 연산으로 나머지 계산한다.
remainder = n % 2

# 나머지 값을 결과 값에 더한다.
bits_sum += remainder

# 몫은 다음 회차 피제수로 사용한다.
n = n // 2

return bits_sum
26 changes: 26 additions & 0 deletions valid-palindrome/liza0525.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# 문자열 길이가 n일 때
# 시간 복잡도: O(n)
# - alphanumeric 확인할 때 전체 문자를 순회하는 게 최대
# 공간 복잡도: O(n)
# - 최악의 경우는 입력 전체가 alphanumeric일 때(특수 문자 없을 때)

class Solution:
# Alphanumeric 스트링 이외의 문자열을 먼저 제외 시킨 이후 lowercase로 변경한 다음, 양 끝에서부터 문자열을 비교한다.
def isPalindrome(self, s: str) -> bool:
only_alnum_s = ''
for ss in s:
if ss.isalnum():
# Alphanumeric이 맞다면 only_alnum_s에 문자열을 더한다.
only_alnum_s += ss

# only_alnum_s 내의 모든 문자를 lowercase로 변경한다.
only_alnum_s = only_alnum_s.lower()

for i in range(len(only_alnum_s) // 2):
# string을 탐색할 index를 0부터 문자열의 반절까지 for문을 돌리며
# 양 끝에서부터 i번 인덱스와 (len(only_alnum) - 1 - i)번 인덱스의 문자 값을 비교한다.
# 같지 않은 경우에는 False로 early return해준다.
if only_alnum_s[i] != only_alnum_s[len(only_alnum_s) - 1 - i]:
return False

return True