diff --git a/198/memo.md b/198/memo.md new file mode 100644 index 0000000..660c1b9 --- /dev/null +++ b/198/memo.md @@ -0,0 +1,20 @@ +# 198. House Robber + +- 動的計画法を書いた + + +https://github.com/naoto-iwase/leetcode/pull/40 +の実装2: without_lastとwith_lastの二変数だけで良い +- sol2.py + +> このコードはスレッドセーフティーという意味でどうなっているでしょうか。 + +- cacheを使う場合(メモ化再帰)、キャッシュはthread safe: multi-threadで使用できる + +https://github.com/hroc135/leetcode/pull/33#discussion_r1899009212 +> フィボナッチになりそうですね。黄金比の n 乗なので 1.6^n くらいです +メモがない場合の計算量 +https://ja.wikipedia.org/wiki/%E3%83%95%E3%82%A3%E3%83%9C%E3%83%8A%E3%83%83%E3%83%81%E6%95%B0 + + +メモ化再帰も書いておく (sol3.py) diff --git a/198/sol1.py b/198/sol1.py new file mode 100644 index 0000000..0f6f474 --- /dev/null +++ b/198/sol1.py @@ -0,0 +1,14 @@ +class Solution: + def rob(self, nums: List[int]) -> int: + if not nums: + raise ValueError("The input list is empty") + + if len(nums) < 2: + return max(nums) + + max_nums = [nums[0], max(nums[0], nums[1])] + [0] * (len(nums) - 2) + + for i in range(2, len(nums)): + max_nums[i] = max(max_nums[i - 1], max_nums[i - 2] + nums[i]) + + return max_nums[-1] diff --git a/198/sol2.py b/198/sol2.py new file mode 100644 index 0000000..02fb250 --- /dev/null +++ b/198/sol2.py @@ -0,0 +1,17 @@ +class Solution: + def rob(self, nums: List[int]) -> int: + if not nums: + raise ValueError("The input list is empty") + + if len(nums) < 2: + return max(nums) + + max_with_last = nums[0] + max_without_last = 0 + + for i in range(1, len(nums)): + next_max_without_last = max_with_last + max_with_last = max(max_with_last, max_without_last + nums[i]) + max_without_last = next_max_without_last + + return max_with_last diff --git a/198/sol3.py b/198/sol3.py new file mode 100644 index 0000000..b755922 --- /dev/null +++ b/198/sol3.py @@ -0,0 +1,16 @@ +from functools import cache + + +class Solution: + def rob(self, nums: List[int]) -> int: + if not nums: + raise ValueError("The input list is empty") + + @cache + def rob_helper(idx): + if idx < 2: + return max(nums[: idx + 1]) + + return max(rob_helper(idx - 1), rob_helper(idx - 2) + nums[idx]) + + return rob_helper(len(nums) - 1)