Skip to content

Commit

Permalink
feat: House Robber #264
Browse files Browse the repository at this point in the history
  • Loading branch information
donghyeon95 authored and donghyeon95 committed Dec 14, 2024
1 parent 27d89c9 commit a41297f
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions house-robber/donghyeon95.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import java.util.Arrays;

class Solution {
private int[] dp;

public int rob(int[] nums) {
// ์ ํ™”์‹
// f(x) = f(๋‚˜๋ฅผ ์„ ํƒ) + f(๋‚˜๋ฅผ ์•ˆ์„ ํƒ)
// 100๊ฐœ๋ผ์„œ ๊ฐ€๋Šฅ์€ ํ•  ๊ฑฐ ๊ฐ™๋‹ค.

dp = new int[100];

// 0๋„ ๊ฐ€๋Šฅ ํ•˜๋‹ค
Arrays.fill(dp, -1);


return recurse(nums, 0);

}

public int recurse(int[] nums, int index) {
// ์ข…๋ฃŒ ์กฐ๊ฑด
if (index >= nums.length) return 0;

// ์ด๋ฏธ ํ•œ๋ฒˆ ์ฒ˜๋ฆฌ๊ฐ€ ๋˜์—ˆ๋‹ค๋ฉด
if (dp[index] != -1) return dp[index];

int result = 0;

// ๋‚˜๋ฅผ ์„ ํƒํ•˜๋Š” ๊ฒฝ์šฐ,
result = Math.max(recurse(nums, index+2)+nums[index], result);

// ๋‚˜๋ฅผ ์„ ํƒํ•˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ,
result = Math.max(recurse(nums, index+1), result);

dp[index] = result;
return result;
}
}

0 comments on commit a41297f

Please sign in to comment.