diff --git a/climbing-stairs/kayden.py b/climbing-stairs/kayden.py new file mode 100644 index 000000000..6b1c1ca33 --- /dev/null +++ b/climbing-stairs/kayden.py @@ -0,0 +1,12 @@ +# 시간복잡도: O(N) +# 공간복잡도: O(N) +class Solution: + def climbStairs(self, n: int) -> int: + dp = [0] * (n + 1) + dp[0] = 1 + dp[1] = 1 + + for i in range(2, n + 1): + dp[i] = dp[i - 1] + dp[i - 2] + + return dp[n] diff --git a/combination-sum/kayden.py b/combination-sum/kayden.py new file mode 100644 index 000000000..af557cd0b --- /dev/null +++ b/combination-sum/kayden.py @@ -0,0 +1,18 @@ +# 시간복잡도: O(N^M) +# 공간복잡도: O(M) +class Solution: + def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: + res = [] + + def dfs(total, idx, path): + if total < 0: + return + elif total == 0: + res.append(path[:]) + + for i in range(idx, len(candidates)): + dfs(total - candidates[i], i, path + [candidates[i]]) + + dfs(target, 0, []) + + return res diff --git a/encode-and-decode-strings/kayden.py b/encode-and-decode-strings/kayden.py index 336048beb..d38dbfb8d 100644 --- a/encode-and-decode-strings/kayden.py +++ b/encode-and-decode-strings/kayden.py @@ -4,26 +4,30 @@ class Solution: # 공간복잡도: O(1) def encode(self, strs): res = "" - for str in strs: - size = len(str) - res += str(size) - res += str + for s in strs: + size = len(s) + res += str(size) + "#" + s # 문자열 크기와 실제 문자열 사이에 구분자 '#'를 추가 return res # 시간복잡도: O(N) # 공간복잡도: O(N) - def decode(self, str): + def decode(self, s): idx = 0 - limit = len(str) + limit = len(s) res = [] while idx < limit: - num = str[idx] - text = "" - for _ in range(num): - text += str[idx] - idx+=1 + # 문자열 길이 파싱 + j = idx + while s[j] != '#': # 구분자 '#'를 찾아 문자열 길이를 추출 + j += 1 + num = int(s[idx:j]) + idx = j + 1 # '#' 다음부터 실제 문자열 시작 + + # 실제 문자열 추출 + text = s[idx:idx + num] res.append(text) + idx += num return res diff --git a/product-of-array-except-self/kayden.py b/product-of-array-except-self/kayden.py new file mode 100644 index 000000000..44e22a8fb --- /dev/null +++ b/product-of-array-except-self/kayden.py @@ -0,0 +1,18 @@ +# 시간복잡도: O(N) +# 공간복잡도: out 제외시 O(1) +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + n = len(nums) + out = [1] * n + + prod = 1 + for i in range(n - 1): + prod *= nums[i] + out[i + 1] *= prod + + prod = 1 + for i in range(n - 1, 0, -1): + prod *= nums[i] + out[i - 1] *= prod + + return out diff --git a/two-sum/kayden.py b/two-sum/kayden.py new file mode 100644 index 000000000..73630185b --- /dev/null +++ b/two-sum/kayden.py @@ -0,0 +1,21 @@ +# 시간복잡도: O(N) +# 공간복잡도: O(N) +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + check = {} + + for idx, num in enumerate(nums): + check[num] = idx + + for idx, num in enumerate(nums): + # 동일한 숫자 두 개가 합쳐져서 목표값이 되는 경우 + if num * 2 == target: + # 그리고 그 숫자가 리스트에 두 개 이상 존재할 경우 + if check[num] != idx: + return [idx, check[num]] + continue + + if target - num in check: + return [check[num], check[target - num]] + + return []