diff --git a/combination-sum/radiantchoi.py b/combination-sum/radiantchoi.py new file mode 100644 index 0000000000..e690488b8b --- /dev/null +++ b/combination-sum/radiantchoi.py @@ -0,0 +1,38 @@ +class Solution: + def traverse(self, candidates: List[int], target: int, result: List[List[int]], current: List[int], starting: int): + # 조건을 만족하는 경우 결과에 추가하고 반환함으로써 콜 스택을 더 이상 쌓지 않음 + if target == 0: + result.append(current[:]) + return + + # 아예 조건을 만족하지 않는 경우 반환함으로써 콜 스택을 더 이상 쌓지 않음 + if target < 0: + return + + # starting 인덱스가 필요한 이유는, 결과 케이스의 원소 순서가 중요하지 않기 때문 + # 즉, [2, 3]과 [3, 2]가 같은 케이스이기 때문 + # 인덱스에 따른 가지치기 적용, 잠재적 중복 케이스 제거 + for i in range(starting, len(candidates)): + candidate = candidates[i] + + # 앞서 투입했던 current 배열을 인-메모리 조작하여 원소 삽입 + current.append(candidate) + + # 콜 스택에 의해, 여기서 호출한 traverse가 먼저 result에 결과를 추가 + # 만약 이 "자식 호출"이 조건을 만족한다면, 위에서 처리하고 반환 + self.traverse(candidates, target - candidate, result, current, i) + + # 인-메모리 조작한 current 배열을 원상복구 + current.pop() + + # 모든 자식 호출을 마무리지은 traverse 함수는 None을 반환 + + def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: + candidates.sort() + + result = [] + current = [] # DFS 수행 중, 현재까지의 결과를 담을 배열 + + self.traverse(candidates, target, result, current, 0) + + return result diff --git a/maximum-subarray/radiantchoi.py b/maximum-subarray/radiantchoi.py new file mode 100644 index 0000000000..b5f9bbd52f --- /dev/null +++ b/maximum-subarray/radiantchoi.py @@ -0,0 +1,14 @@ +class Solution: + def maxSubArray(self, nums: List[int]) -> int: + n = len(nums) + + # 원래라면 dp 배열을 만들어, i번째 원소까지 탐색한 결과 중 최댓값을 각각의 인덱스에 저장 + # 하지만 지금은 최댓값만 남기면 되므로 일차적 최적화 + current = nums[0] + result = nums[0] + + for i in range(1, len(nums)): + current = max(current + nums[i], nums[i]) + result = max(result, current) + + return result diff --git a/number-of-1-bits/radiantchoi.py b/number-of-1-bits/radiantchoi.py new file mode 100644 index 0000000000..e7d7275090 --- /dev/null +++ b/number-of-1-bits/radiantchoi.py @@ -0,0 +1,4 @@ +class Solution: + def hammingWeight(self, n: int) -> int: + # n을 2진수로 변환한 문자열에서 1의 갯수를 반환 + return len(list(filter(lambda x: x == "1", bin(n)[2:]))) diff --git a/valid-palindrome/radiantchoi.py b/valid-palindrome/radiantchoi.py new file mode 100644 index 0000000000..6b68fa4b3c --- /dev/null +++ b/valid-palindrome/radiantchoi.py @@ -0,0 +1,12 @@ +class Solution: + def isPalindrome(self, s: str) -> bool: + # 선제적으로 소문자로 바꾼 문자열에서 알파벳이나 숫자인지를 걸러 낸다. + s = list(filter(lambda x: x.isalnum(), s.lower())) + + # 처음과 끝에서 각각 한 칸씩 좁혀지는 인덱스의 구현을 위해 배열의 절반까지만 순회 + # 같은 위계에 있는 글자가 같지 않을 경우 early return + for i in range(len(s) // 2): + if s[i] != s[len(s) - i - 1]: + return False + + return True