Skip to content

Commit 907b4b6

Browse files
authored
Merge pull request #1636 from soobing/week14
[soobing] WEEK14 Solutions
2 parents 5472958 + aafbd39 commit 907b4b6

File tree

5 files changed

+212
-0
lines changed

5 files changed

+212
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* 문제 설명
3+
* - 이진 트리의 레벨 순서 순회 문제
4+
*
5+
* 아이디어
6+
* 1) BFS 레벨 순서별로 큐에 넣어서 탐색하며 결과를 반환
7+
*
8+
*/
9+
/**
10+
* Definition for a binary tree node.
11+
* class TreeNode {
12+
* val: number
13+
* left: TreeNode | null
14+
* right: TreeNode | null
15+
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
16+
* this.val = (val===undefined ? 0 : val)
17+
* this.left = (left===undefined ? null : left)
18+
* this.right = (right===undefined ? null : right)
19+
* }
20+
* }
21+
*/
22+
23+
function levelOrder(root: TreeNode | null): number[][] {
24+
if (!root) return [];
25+
26+
const queue: TreeNode[] = [root];
27+
const result: number[][] = [];
28+
29+
while (queue.length) {
30+
const levelSize = queue.length;
31+
const currentLevel: number[] = [];
32+
for (let i = 0; i < levelSize; i++) {
33+
const node = queue.shift()!;
34+
currentLevel.push(node.val);
35+
36+
if (node.left) queue.push(node.left);
37+
if (node.right) queue.push(node.right);
38+
}
39+
40+
result.push(currentLevel);
41+
}
42+
return result;
43+
}

counting-bits/soobing.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
/**
2+
* 문제 설명
3+
* - 0부터 n까지의 모든 수에 대해 이진수에서 1의 개수를 세는 함수를 작성하라.
4+
*
5+
* 아이디어
6+
* 1) DP + 비트연산
7+
* - ans[i] = ans[i >> 1] + (i & 1)
8+
*/
9+
function countBits(n: number): number[] {
10+
const ans = Array(n + 1).fill(0);
11+
for (let i = 1; i <= n; i++) {
12+
ans[i] = ans[i >> 1] + (i & 1);
13+
}
14+
return ans;
15+
}

house-robber/soobing.ts

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* 문제 설명
3+
* - 주어진 배열의 시작과 끝이 연결되어 있는 원형이라고 할 경우에, 이웃하는 집은 털 수 없고 최대로 털 수 있는 돈을 구하는 문제
4+
*
5+
* 아이디어
6+
* 1) 동적 계획법(Dynamic Programming) 활용
7+
* - 원형 구조이므로 첫번째 집과 마지막집은 동시에 털 수 없음
8+
* - 따라서 두 가지 경우로 나누어 계산하고, 두 결과 중 더 큰 값을 반환
9+
* 2) 선형 배열에 대한 최대 금액 계산
10+
* - 매 순회마다 현재 집을 털 경우(prev2 + num)와 털지 않을 경우(prev1) 중 큰 값을 선택
11+
* - 최종적으로 prev1에 최대값이 저장
12+
*/
13+
function robLinear(nums: number[]) {
14+
let prev1 = 0;
15+
let prev2 = 0;
16+
17+
for (const num of nums) {
18+
const temp = prev1;
19+
prev1 = Math.max(prev2 + num, prev1);
20+
prev2 = temp;
21+
}
22+
23+
return prev1;
24+
}
25+
26+
function rob(nums: number[]): number {
27+
if (nums.length === 1) return nums[0];
28+
if (nums.length === 2) return Math.max(nums[0], nums[1]);
29+
30+
const temp1 = robLinear(nums.slice(0, nums.length - 1));
31+
const temp2 = robLinear(nums.slice(1));
32+
33+
return Math.max(temp1, temp2);
34+
}

meeting-rooms-ii/soobing.ts

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* 문제 설명
3+
* - 주어진 회의시간을 진행할 수 있는 최소의 회의시간 갯수 구하기
4+
*
5+
* 아이디어
6+
* 1) minheap + greeday
7+
* - 회의시간 시작시간으로 정렬(회의 일정을 시간 순으로 처리)
8+
* - Heap에는 현재 사용 중인 회의실의 종료 시간들만 저장
9+
* - 회의 시작시간이 끝시간보다 같거나 크면 회의실 쓸수 있는 거니까 shift 해서 회의 꺼냄
10+
* - 회의시간 끝 시간을 힙에 넣고, 끝시간 오름차순으로 정렬(minheap)
11+
* - 최종적으로 heap의 크기 = 필요한 회의실 개수
12+
*/
13+
14+
type Interval = { start: number; end: number };
15+
16+
class Solution {
17+
minMeetingRooms(intervals: Interval[]): number {
18+
if (intervals.length === 0) return 0;
19+
20+
intervals.sort((a, b) => a.start - b.start);
21+
22+
const heap: number[] = [];
23+
24+
for (const interval of intervals) {
25+
const { start, end } = interval;
26+
27+
if (heap.length > 0 && heap[0] <= start) {
28+
heap.shift();
29+
}
30+
31+
heap.push(end);
32+
heap.sort((a, b) => a - b);
33+
}
34+
35+
return heap.length;
36+
}
37+
}

word-search-ii/soobing.ts

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
/**
2+
* 문제 설명
3+
* - 2차원 배열에서 주어진 단어들을 찾는 문제
4+
*
5+
* 아이디어
6+
* 1) Trie 자료구조 + DFS & Backtracking (👀어려웠음..다시 풀어보기)
7+
* - 주어진 단어들을 Trie 자료구조로 변환
8+
* - 2차원 배열을 순회하면서 Trie 자료구조를 사용하여 단어를 찾음
9+
* - 찾은 단어는 배열에 추가
10+
*/
11+
class TrieNode {
12+
private nodes = new Map<string, TrieNode>();
13+
word: string | null = null;
14+
15+
add(word: string) {
16+
let currentNode = this as TrieNode;
17+
for (const char of word) {
18+
if (!currentNode.nodes.has(char)) {
19+
currentNode.nodes.set(char, new TrieNode());
20+
}
21+
currentNode = currentNode.nodes.get(char)!;
22+
}
23+
currentNode.word = word;
24+
}
25+
26+
getNode(char: string) {
27+
return this.nodes.get(char);
28+
}
29+
30+
hasChar(char: string) {
31+
return this.nodes.has(char);
32+
}
33+
}
34+
35+
function search(
36+
m: number,
37+
n: number,
38+
board: string[][],
39+
node: TrieNode,
40+
result: string[]
41+
) {
42+
const M = board.length;
43+
const N = board[0].length;
44+
if (m < 0 || m >= M || n < 0 || n >= N) return;
45+
46+
const currentChar = board[m][n];
47+
if (currentChar === "#" || !node.hasChar(currentChar)) return;
48+
49+
node = node.getNode(currentChar)!;
50+
51+
if (node.word) {
52+
result.push(node.word);
53+
node.word = null;
54+
}
55+
56+
board[m][n] = "#";
57+
58+
search(m + 1, n, board, node, result);
59+
search(m - 1, n, board, node, result);
60+
search(m, n + 1, board, node, result);
61+
search(m, n - 1, board, node, result);
62+
63+
board[m][n] = currentChar;
64+
}
65+
66+
function findWords(board: string[][], words: string[]): string[] {
67+
const root = new TrieNode();
68+
for (const word of words) {
69+
root.add(word);
70+
}
71+
72+
const result: string[] = [];
73+
const M = board.length;
74+
const N = board[0].length;
75+
76+
for (let i = 0; i < M; i++) {
77+
for (let j = 0; j < N; j++) {
78+
search(i, j, board, root, result);
79+
}
80+
}
81+
82+
return result;
83+
}

0 commit comments

Comments
 (0)