From 48648437ae0f56cf1d0798dfc42a5fd16cae87fe Mon Sep 17 00:00:00 2001 From: potrue <126231160+potrue@users.noreply.github.com> Date: Tue, 5 Aug 2025 17:03:49 +0900 Subject: [PATCH] 198. House Robber MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 問題文: https://leetcode.com/problems/house-robber/description/ --- 198/198.md | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 198/198.md diff --git a/198/198.md b/198/198.md new file mode 100644 index 0000000..bca6e31 --- /dev/null +++ b/198/198.md @@ -0,0 +1,59 @@ +## 何も見ずに解いてみる + +```cpp +class Solution { +public: + int rob(std::vector& nums) { + int max_with_last_broken = 0; + int max_with_last_unbroken = 0; + for (const int num : nums) { + int next_max_with_last_broken = max_with_last_unbroken + num; + int next_max_with_last_unbroken = std::max(max_with_last_broken, max_with_last_unbroken); + max_with_last_broken = next_max_with_last_broken; + max_with_last_unbroken = next_max_with_last_unbroken; + } + return std::max(max_with_last_broken, max_with_last_unbroken); + } +}; +``` + +## 他の人のコードを見てみる + +https://github.com/tokuhirat/LeetCode/pull/35/files +https://github.com/irohafternoon/LeetCode/pull/38/files +https://github.com/Ryotaro25/leetcode_first60/pull/36/files +https://github.com/Jikuhara/LeetCode/pull/7/files + +下のようにすれば変数は3つで書くことができた。 +ただ、どの値がどの値に依存しているか気にしなくて良いという意味では変数を4つ用意してしまった方が読みやすい気もする。 + +```cpp + for (const int num : nums) { + int next_max_with_last_broken = max_with_last_unbroken + num; + max_with_last_unbroken = std::max(max_with_last_broken, max_with_last_unbroken); + max_with_last_broken = next_max_with_last_broken; + } +``` + +変数名について、lastという言い方はnumsの中の一番最後という位置を連想してしまうかもしれない。prevなどの方が良いかも? + +一次元DPを見て思ったが、もしかしたら最後に入っているか入っていないかで変数を分けるよりも、単純に一個前までのmax、二個前までのmaxとして変数に保存した方がわかりやすいかもしれない。 +ただ、抽象的になりすぎて何のことかわからなくなる可能性はありそうで悩ましい・・・ + +## 最終コード + +```cpp +class Solution { +public: + int rob(std::vector& nums) { + int prev_max = 0; + int current_max = 0; + for (const int num : nums) { + int next_max = std::max(current_max, prev_max + num); + prev_max = current_max; + current_max = next_max; + } + return current_max; + } +}; +```