Table of Contents
337. House Robber III
https://leetcode.com/problems/house-robber-iii/
Recursion, DFS
class Solution {
public int rob(TreeNode root) {
if(root == null) return 0;
int[] res = dfs(root);
return Math.max(res[0], res[1]);
}
public int[] dfs(TreeNode root) {
if(root == null) return new int[]{0,0};
// curMax[0] represents max value without robbing current node,
// curMax[1] represents max value with robbing current node;
int[] curMax = new int[2];
int[] leftMax = dfs(root.left);
int[] rightMax = dfs(root.right);
curMax[0] = Math.max(leftMax[0], leftMax[1]) + Math.max(rightMax[0], rightMax[1]);
curMax[1] = leftMax[0] + rightMax[0] + root.val;
return curMax;
}
}
338. Counting Bits
https://leetcode.com/problems/counting-bits/
DP
class Solution {
public int[] countBits(int num) {
int[] dp = new int[num + 1];
dp[0] = 0;
int offset = 1;
for(int i = 1; i <= num; i++) {
if(offset * 2 == i) {
offset *= 2;
}
dp[i] = dp[i - offset] + 1;
}
return dp;
}
}
/*
8 1000
9 1001
10 1010
11 1011
12 1100
13 1101
14 1110 -> 1 110 -> dp[6] + 1 = dp[14 - 8] + 1
15 1111 -> 1 111 -> dp[7] + 1 = dp[15 - 8] + 1
dp[i] = dp[i - offset] + 1; offset = largest 2^n before i;
*/
347. Top K Frequent Elements
https://leetcode.com/problems/top-k-frequent-elements/
Array
Bucket Sort
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
for(int num : nums) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
List<Integer>[] bucket = new List[nums.length + 1];
for(int i : map.keySet()) {
int freq = map.get(i);
if(bucket[freq] == null) {
bucket[freq] = new ArrayList<>();
}
bucket[freq].add(i);
}
int[] res = new int[k];
for(int i = nums.length; i > 0; i--) {
if(bucket[i] != null) {
int size = bucket[i].size();
while(size > 0 && k > 0) {
res[k - 1] = bucket[i].get(size - 1);
size--;
k--;
}
}
if(k == 0) {
break;
}
}
return res;
}
}
394. Decode String
https://leetcode.com/problems/decode-string/
Stack
class Solution {
public String decodeString(String s) {
Deque<Integer> count = new ArrayDeque<>();
Deque<String> result = new ArrayDeque<>();
int i = 0;
result.push("");
while (i < s.length()) {
char ch = s.charAt(i);
if (Character.isDigit(ch)) {
int times = ch - '0';
while (Character.isDigit(s.charAt(i + 1))) {
times = 10 * times + (s.charAt(i + 1) - '0');
i++;
}
count.push(times);
} else if (ch == '[') {
result.push("");
} else if (ch == ']') {
String str = result.pop();
StringBuilder sb = new StringBuilder();
int times = count.pop();
for (int j = 0; j < times; j++) {
sb.append(str);
}
result.push(result.pop() + sb.toString());
} else {
result.push(result.pop() + ch);
}
i++;
}
return result.pop();
}
}