diff --git a/14. Questions/leetcode 427 - construct quad tree.py b/14. Questions/leetcode 427 - construct quad tree.py new file mode 100644 index 0000000..f2dba66 --- /dev/null +++ b/14. Questions/leetcode 427 - construct quad tree.py @@ -0,0 +1,37 @@ +# construct quad tree | leetcode 427 | https://leetcode.com/problems/construct-quad-tree/ +# recursively call each quad of the grid and check if each quad is uniform or not + +# Definition for a QuadTree node. +class Node: + def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight): + self.val = val + self.isLeaf = isLeaf + self.topLeft = topLeft + self.topRight = topRight + self.bottomLeft = bottomLeft + self.bottomRight = bottomRight + + +class Solution: + def construct(self, grid: list[list[int]]) -> Node: + def checkThisQuad(row, col, n) -> bool: + for i in range(row, row + n): + for j in range(col, col + n): + if grid[i][j] != grid[row][col]: + return False + return True + + def quadTree(row, col, n): + if checkThisQuad(row, col, n): + return Node(grid[row][col], 1, None, None, None, None) + + + return Node(grid[row][col], 0, + quadTree(row, col, n//2), + quadTree(row, col + n//2, n//2), + quadTree(row + n//2, col, n//2), + quadTree(row + n//2, col + n//2, n//2) + ) + + return quadTree(0, 0, len(grid)) + diff --git a/14. Questions/leetcode 494 - target sum.py b/14. Questions/leetcode 494 - target sum.py new file mode 100644 index 0000000..ddc9e1b --- /dev/null +++ b/14. Questions/leetcode 494 - target sum.py @@ -0,0 +1,22 @@ +# target sum | leetcode 494 | https://leetcode.com/problems/target-sum/ +# 0/1 knapsack to decide +/- and cache (index, total) + +class Solution: + def findTargetSumWays(self, nums: list[int], target: int) -> int: + N = len(nums) + mem = dict() + + if N == 0: + return 0 + + def knapsack(n, s): + if n == N: + return 1 if s == target else 0 + + if (n, s) in mem: + return mem[(n, s)] + + mem[(n, s)] = knapsack(n+1, s + nums[n]) + knapsack(n+1, s - nums[n]) + return mem[(n, s)] + + return knapsack(0, 0)