Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 484e08a

Browse files
Merge pull request #22 from mihirs16/master
added leetcode questions
2 parents c7c4498 + 40c285c commit 484e08a

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# construct quad tree | leetcode 427 | https://leetcode.com/problems/construct-quad-tree/
2+
# recursively call each quad of the grid and check if each quad is uniform or not
3+
4+
# Definition for a QuadTree node.
5+
class Node:
6+
def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):
7+
self.val = val
8+
self.isLeaf = isLeaf
9+
self.topLeft = topLeft
10+
self.topRight = topRight
11+
self.bottomLeft = bottomLeft
12+
self.bottomRight = bottomRight
13+
14+
15+
class Solution:
16+
def construct(self, grid: list[list[int]]) -> Node:
17+
def checkThisQuad(row, col, n) -> bool:
18+
for i in range(row, row + n):
19+
for j in range(col, col + n):
20+
if grid[i][j] != grid[row][col]:
21+
return False
22+
return True
23+
24+
def quadTree(row, col, n):
25+
if checkThisQuad(row, col, n):
26+
return Node(grid[row][col], 1, None, None, None, None)
27+
28+
29+
return Node(grid[row][col], 0,
30+
quadTree(row, col, n//2),
31+
quadTree(row, col + n//2, n//2),
32+
quadTree(row + n//2, col, n//2),
33+
quadTree(row + n//2, col + n//2, n//2)
34+
)
35+
36+
return quadTree(0, 0, len(grid))
37+
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# target sum | leetcode 494 | https://leetcode.com/problems/target-sum/
2+
# 0/1 knapsack to decide +/- and cache (index, total)
3+
4+
class Solution:
5+
def findTargetSumWays(self, nums: list[int], target: int) -> int:
6+
N = len(nums)
7+
mem = dict()
8+
9+
if N == 0:
10+
return 0
11+
12+
def knapsack(n, s):
13+
if n == N:
14+
return 1 if s == target else 0
15+
16+
if (n, s) in mem:
17+
return mem[(n, s)]
18+
19+
mem[(n, s)] = knapsack(n+1, s + nums[n]) + knapsack(n+1, s - nums[n])
20+
return mem[(n, s)]
21+
22+
return knapsack(0, 0)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /