From 92992f05904788e8249f142f2b3eb5b6ad1c5ec4 Mon Sep 17 00:00:00 2001 From: zhenzi Date: Sat, 15 May 2021 11:43:00 +0800 Subject: [PATCH] =?UTF-8?q?0198=20=E6=89=93=E5=AE=B6=E5=8A=AB=E8=88=8D?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20Java=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0198.打家劫舍.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/problems/0198.打家劫舍.md b/problems/0198.打家劫舍.md index c64648ad..649dd055 100644 --- a/problems/0198.打家劫舍.md +++ b/problems/0198.打家劫舍.md @@ -111,7 +111,24 @@ public: Java: +```Java +// 动态规划 +class Solution { + public int rob(int[] nums) { + if (nums == null || nums.length == 0) return 0; + if (nums.length == 1) return nums[0]; + int[] dp = new int[nums.length + 1]; + dp[0] = nums[0]; + dp[1] = Math.max(dp[0], nums[1]); + for (int i = 2; i < nums.length; i++) { + dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]); + } + + return dp[nums.length - 1]; + } +} +``` Python: