|
| 1 | +import java.util.HashMap; |
| 2 | +import java.util.Map; |
| 3 | + |
| 4 | +// 시간복잡도: O(n) |
| 5 | +// TODO: DP 방식으로 풀어보기 |
| 6 | +class Solution { |
| 7 | + public Map<Integer, Integer> robMap = new HashMap<>(); |
| 8 | + public int rob(int[] nums) { |
| 9 | + return dfs(nums, 0); |
| 10 | + } |
| 11 | + |
| 12 | + public int dfs(int[] nums, int index) { |
| 13 | + if(nums.length == 0) { |
| 14 | + return 0; |
| 15 | + } |
| 16 | + |
| 17 | + if(index >= nums.length) { |
| 18 | + return 0; |
| 19 | + } |
| 20 | + |
| 21 | + // 이미 털었던 집이라면, 해 |
| 22 | + if(robMap.containsKey(index)) { |
| 23 | + return robMap.get(index); |
| 24 | + } |
| 25 | + |
| 26 | + // 이번 집을 털게되는 경우 |
| 27 | + int robThis = nums[index] + dfs(nums, index + 2); |
| 28 | + |
| 29 | + // 이번 집을 털지않고 건너뛰는 경우,. |
| 30 | + int skipThis = dfs(nums, index + 1); |
| 31 | + |
| 32 | + robMap.put(index, Math.max(robThis, skipThis)); |
| 33 | + |
| 34 | + return robMap.get(index); |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +// TODO: 비효율적으로 작성한 알고리즘의 동작 방식을 도식화 해서 그려보기. |
| 39 | +// NOTE: dfs를 사용한 완전탐색 |
| 40 | +// 탐색 방식이 매우 비효율적이라, 정답은 맞추지만 N이 커지면 시간초과 |
| 41 | +// 시간복잡도: O(2^n) + alpha(중복탐색) |
| 42 | +class WrongSolution { |
| 43 | + public boolean[] visit; |
| 44 | + public int mx = -987654321; |
| 45 | + public int curSum = 0; |
| 46 | + |
| 47 | + public int rob(int[] nums) { |
| 48 | + if(nums.length == 1) { |
| 49 | + return nums[0]; |
| 50 | + } |
| 51 | + |
| 52 | + visit = new boolean[nums.length]; |
| 53 | + dfs(nums, 0); |
| 54 | + dfs(nums, 1); |
| 55 | + |
| 56 | + return mx; |
| 57 | + } |
| 58 | + |
| 59 | + public void dfs(int[] arr, int idx) { |
| 60 | + int len = arr.length; |
| 61 | + int prevIdx = idx - 1; |
| 62 | + int nextIdx = idx + 1; |
| 63 | + |
| 64 | + |
| 65 | + if(idx == 0) { |
| 66 | + if(visit[idx]) return; |
| 67 | + } else { |
| 68 | + if(idx >= len || visit[idx] || visit[prevIdx]) { |
| 69 | + return; |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + visit[idx] = true; |
| 74 | + curSum += arr[idx]; |
| 75 | + mx = Math.max(mx, curSum); |
| 76 | + |
| 77 | + for(int i = idx; i < len; i++) { |
| 78 | + dfs(arr, i); |
| 79 | + } |
| 80 | + |
| 81 | + visit[idx] = false; |
| 82 | + curSum -= arr[idx]; |
| 83 | + } |
| 84 | +} |
0 commit comments