Skip to content

Commit f333b6b

Browse files
committed
add longest-increasing-subsequence, spiral-matrix
1 parent cf362f5 commit f333b6b

File tree

3 files changed

+90
-1
lines changed

3 files changed

+90
-1
lines changed

design-add-and-search-words-data-structure/i-mprovising.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ def dfs(self, start, word):
3030
ch = word[0]
3131
if ch == word:
3232
if ch == '.':
33-
return any([node.end for c, node in start.children.items()])
33+
return any([node.end for node in start.children.values()])
3434
elif ch in start.children:
3535
if start.children[ch].end:
3636
return True
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
"""
2+
Time complexity O(n^2)
3+
Space complexity O(n)
4+
5+
Dynamic programming
6+
"""
7+
8+
class Solution:
9+
def lengthOfLIS(self, nums: List[int]) -> int:
10+
11+
dp = [(1, nums[0])] # sequence len, max num in sequence
12+
13+
for i in range(1, len(nums)):
14+
num = nums[i]
15+
max_len = 1
16+
for j in range(i):
17+
x, y = dp[j]
18+
if y < num:
19+
if max_len < x + 1:
20+
max_len = x + 1
21+
dp.append((max_len, num))
22+
23+
# find max len
24+
max_len = 0
25+
for x in dp:
26+
if x[0] > max_len:
27+
max_len = x[0]
28+
29+
return max_len

spiral-matrix/i-mprovising.py

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
"""
2+
Time complexity O(m*n)
3+
4+
단순구현
5+
"""
6+
7+
class Solution:
8+
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
9+
"""
10+
111
11+
1M1 visited
12+
111
13+
"""
14+
m, n = len(matrix), len(matrix[0])
15+
16+
board = [[0] * (n+2)]
17+
for i in range(m):
18+
tmp = [0] + matrix[i] + [0]
19+
board.append(tmp)
20+
board.append([0] * (n+2))
21+
22+
visited = [[True] * (n+1)]
23+
for _ in range(m):
24+
tmp = [True] + [False] * n + [True]
25+
visited.append(tmp)
26+
visited.append([True] * (n+1))
27+
28+
direction = 0
29+
x, y = 1, 1
30+
numbers = []
31+
32+
for _ in range(m * n):
33+
numbers.append(board[x][y])
34+
visited[x][y] = True
35+
36+
i, j = self.next_idx(direction, x, y)
37+
if visited[i][j]:
38+
direction = self.change_dir(direction)
39+
x, y = self.next_idx(direction, x, y)
40+
else:
41+
x, y = i, j
42+
43+
return numbers
44+
45+
def next_idx(self, dir, x, y):
46+
"""
47+
0 1 2 3 : R D L U
48+
"""
49+
if dir == 0:
50+
y += 1
51+
elif dir == 1:
52+
x += 1
53+
elif dir == 2:
54+
y -= 1
55+
else:
56+
x -= 1
57+
return x, y
58+
59+
def change_dir(self, dir):
60+
return (dir + 1) % 4

0 commit comments

Comments
 (0)