Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[EGON] Week 02 Solutions #367

Merged
merged 5 commits into from
Aug 25, 2024
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
47 changes: 47 additions & 0 deletions climbing-stairs/EGON.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
from unittest import TestCase, main


class Solution:
def climbStairs(self, n: int) -> int:
return self.solveWithDP(n)

"""
Runtime: 30 ms (Beats 83.62%)
Time Complexity: O(n)
> 3에서 n + 1 까지 range를 조회하였으므로 O((n + 1) - 3) ~= O(n)

Memory: 16.39 MB (Beats 90.15%)
Space Complexity: O(n)
> 크기가 n + 1인 dp를 선언하여 사용했으므로 O(n + 1) ~= O(n)
"""
def solveWithDP(self, n: int) -> int:
if n <= 2:
return n

dp = [0] * (n + 1)
dp[0], dp[1], dp[2] = 0, 1, 2
for stair in range(3, n + 1):
dp[stair] = dp[stair - 1] + dp[stair - 2]

return dp[n]


class _LeetCodeTestCases(TestCase):
def test_1(self):
n = 2
output = 2
self.assertEqual(Solution.climbStairs(Solution(), n), output)

def test_2(self):
n = 3
output = 3
self.assertEqual(Solution.climbStairs(Solution(), n), output)

def test_3(self):
n = 1
output = 1
self.assertEqual(Solution.climbStairs(Solution(), n), output)


if __name__ == '__main__':
main()
65 changes: 65 additions & 0 deletions coin-change/EGON.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
from typing import List
from unittest import TestCase, main
from collections import defaultdict


class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
return self.solve_with_dp(coins, amount)

# Unbounded Knapsack Problem
def solve_with_dp(self, coins: List[int], amount: int) -> int:
if amount == 0:
return 0

coins.sort()

if amount < coins[0]:
return -1

dp = [[0] * (amount + 1) for _ in range(len(coins) + 1)]
for curr_r in range(1, len(coins) + 1):
coin_index = curr_r - 1
curr_coin = coins[coin_index]
if amount < curr_coin:
continue

dp[curr_r][curr_coin] += 1
for curr_amount in range(curr_coin + 1, amount + 1):
for coin in coins:
if 0 < dp[curr_r][curr_amount - coin]:
dp[curr_r][curr_amount] = max(dp[curr_r - 1][curr_amount], dp[curr_r][curr_amount - coin] + 1)
else:
dp[curr_r][curr_amount] = dp[curr_r - 1][curr_amount]

return dp[-1][-1] if 0 < dp[-1][-1] else -1


class _LeetCodeTestCases(TestCase):
def test_1(self):
coins = [1, 2, 5]
amount = 11
output = 3
self.assertEqual(Solution.coinChange(Solution(), coins, amount), output)

def test_2(self):
coins = [2]
amount = 3
output = -1
self.assertEqual(Solution.coinChange(Solution(), coins, amount), output)

def test_3(self):
coins = [1]
amount = 0
output = 0
self.assertEqual(Solution.coinChange(Solution(), coins, amount), output)

def test_4(self):
coins = [1, 2147483647]
amount = 2
output = -1
self.assertEqual(Solution.coinChange(Solution(), coins, amount), output)


if __name__ == '__main__':
main()
63 changes: 63 additions & 0 deletions combination-sum/EGON.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
from typing import List
from unittest import TestCase, main
from collections import defaultdict


class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
return self.solve_with_dfs(candidates, target)

"""
Runtime: 2039 ms (Beats 5.01%)
Time Complexity: ?

Memory: 16.81 MB (Beats 11.09%)
Space Complexity: ?
"""
def solve_with_dfs(self, candidates: List[int], target: int) -> List[List[int]]:
result = []
stack = []
visited = defaultdict(bool)
for candidate in candidates:
stack.append([[candidate], candidate])

while stack:
curr_combination, curr_sum = stack.pop()
curr_visited_checker = tuple(sorted(curr_combination))

if curr_sum == target and visited[curr_visited_checker] is False:
visited[curr_visited_checker] = True
result.append(curr_combination)

if target < curr_sum:
continue

for candidate in candidates:
post_combination, post_sum = curr_combination + [candidate], curr_sum + candidate
stack.append([post_combination, post_sum])

return result


class _LeetCodeTestCases(TestCase):
def test_1(self):
candidates = [2, 3, 6, 7]
target = 7
output = [[2, 2, 3], [7]]
self.assertEqual(Solution.combinationSum(Solution(), candidates, target), output)

def test_2(self):
candidates = [2, 3, 5]
target = 8
output = [[2, 2, 2, 2], [2, 3, 3], [3, 5]]
self.assertEqual(Solution.combinationSum(Solution(), candidates, target), output)

def test_3(self):
candidates = [2]
target = 1
output = []
self.assertEqual(Solution.combinationSum(Solution(), candidates, target), output)


if __name__ == '__main__':
main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
from typing import List, Optional
from unittest import TestCase, main


# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right


class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
return self.solve_1(preorder, inorder)

"""
Runtime: 112 ms (Beats 66.16%)
Time Complexity: O(n ** 2)
Space Complexity: O(n)
Memory: 52.83 MB (Beats 63.14%)
"""
def solve_1(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
index = 0

def build_tree(preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
nonlocal index

if not inorder:
return None

if not 0 <= index < len(preorder):
return None

root = TreeNode(preorder[index])
index += 1
split_index = inorder.index(root.val)
root.left = build_tree(preorder, inorder[:split_index])
root.right = build_tree(preorder, inorder[split_index + 1:])

return root

return build_tree(preorder, inorder)


class _LeetCodeTestCases(TestCase):
def test_1(self):
preorder = [3, 9, 20, 15, 7]
inorder = [9, 3, 15, 20, 7]
output = TreeNode(
val=3,
left=TreeNode(
val=9
),
right=TreeNode(
val=20,
left=TreeNode(val=15),
right=TreeNode(val=7)
)
)
self.assertEqual(Solution.buildTree(Solution(), preorder, inorder), output)

def test_2(self):
preorder = [-1]
inorder = [-1]
output = TreeNode(
val=-1
)
self.assertEqual(Solution.buildTree(Solution(), preorder, inorder), output)

def test_3(self):
preorder = [1, 2]
inorder = [1, 2]
output = TreeNode(
val=1,
right=TreeNode(
val=2
)
)
self.assertEqual(Solution.buildTree(Solution(), preorder, inorder), output)


if __name__ == '__main__':
main()
39 changes: 39 additions & 0 deletions counting-bits/EGON.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
from typing import List
from unittest import TestCase, main


class Solution:
def countBits(self, n: int) -> List[int]:
return self.solve_1(n)

"""
Runtime: 78 ms (Beats 31.22%)
Time Complexity: O(n * log n), 크기가 n인 배열의 원소들에 대해 시행마다 크기가 2로 나누어지는 비트연산을 수행하므로
Space Complexity: O(1), 변수 저장 없이 바로 결과 반환
Memory: 23.26 MB (Beats 39.52%)
"""
def solve_1(self, n: int) -> List[int]:
def count_number_of_1(n: int):
count = 0
while n:
n &= (n - 1)
count += 1
return count

return [count_number_of_1(num) for num in range(n + 1)]


class _LeetCodeTestCases(TestCase):
def test_1(self):
n = 2
output = [0, 1, 1]
self.assertEqual(Solution.countBits(Solution(), n), output)

def test_2(self):
n = 5
output = [0, 1, 1, 2, 1, 2]
self.assertEqual(Solution.countBits(Solution(), n), output)


if __name__ == '__main__':
main()
Loading