diff --git a/combination-sum/changhyumm.py b/combination-sum/changhyumm.py new file mode 100644 index 0000000000..e6a9bd286a --- /dev/null +++ b/combination-sum/changhyumm.py @@ -0,0 +1,19 @@ +class Solution: + def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: + ans = [] + def combination(index, cur_comb, cur_sum): + if cur_sum == target: + ans.append(cur_comb[:]) + return + if cur_sum > target or index >= len(candidates): + return + cur_comb.append(candidates[index]) + combination(index, cur_comb, cur_sum + candidates[index]) + # 합이 target이랑 같던지, 크던지, 길이를 넘던지하면 return으로 탈출 + # 그 외에 다른 경우의 수를 봐야하므로 + # 마지막꺼는 다시 빼고 어쨌든 index 넘겨서 다시 combination 확인해봐야함 + cur_comb.pop() + combination(index + 1, cur_comb, cur_sum) + return ans + + return combination(0, [], 0) diff --git a/decode-ways/changhyumm.py b/decode-ways/changhyumm.py new file mode 100644 index 0000000000..39c5664c6d --- /dev/null +++ b/decode-ways/changhyumm.py @@ -0,0 +1,30 @@ +class Solution: + def numDecodings(self, s: str) -> int: + memo = {} + + def decode(index): + # 이미 계산했으면 바로 반환 + if index in memo: + return memo[index] + + # 기저 사례 + ## 끝까지 왔으면 성공 + if index == len(s): + return 1 + ## 0으로 시작하면 불가능 + if s[index] == '0': + return 0 + + # 재귀 계산 + ways = decode(index + 1) + + if index + 1 < len(s) and int(s[index:index+2]) <= 26: + ways += decode(index + 2) + + # 메모이제이션 + memo[index] = ways + return ways + + # 시간복잡도, 공간복잡도 O(n) + + return decode(0) diff --git a/maximum-subarray/changhyumm.py b/maximum-subarray/changhyumm.py new file mode 100644 index 0000000000..b61abf7208 --- /dev/null +++ b/maximum-subarray/changhyumm.py @@ -0,0 +1,14 @@ +class Solution: + def maxSubArray(self, nums: List[int]) -> int: + max_total = nums[0] + total = 0 + # subarray는 array에서 서로 인접해야함 + # 인접한 값의 합이 마이너스인 경우, 그냥 현재 값만 사용하는게 합보다 큼 + # total 이 0보다 작은경우 그냥 0으로 변경 + for num in nums: + if total < 0: + total = 0 + total += num + max_total = max(total, max_total) + # 시간복잡도 O(n), 공간복잡도 O(1) + return max_total diff --git a/number-of-1-bits/changhyumm.py b/number-of-1-bits/changhyumm.py new file mode 100644 index 0000000000..ccd6e0b387 --- /dev/null +++ b/number-of-1-bits/changhyumm.py @@ -0,0 +1,11 @@ +class Solution: + def hammingWeight(self, n: int) -> int: + count = 0 + # 시간복잡도 O(log n) 반으로 나누기 때문 + while n > 0: + if n % 2 == 1: + count += 1 + n = n // 2 + else: + n = n / 2 + return count diff --git a/valid-palindrome/changhyumm.py b/valid-palindrome/changhyumm.py new file mode 100644 index 0000000000..d3e2fb7e2a --- /dev/null +++ b/valid-palindrome/changhyumm.py @@ -0,0 +1,11 @@ +class Solution: + def isPalindrome(self, s: str) -> bool: + # 시간복잡도 O(n) + # loop + s_list = [x.lower() for x in s if x.isalnum()] + # 시간복잡도 O(n) + # loop + list pop() + for i in range(len(s_list)//2): + if s_list[i] != s_list.pop(): + return False + return True