wanghsinche / essay

All about my technical essays and practicals
https://wanghsinche.github.io/essay/
0 stars 0 forks source link

Some paradigms for leetcode questions #1

Open wanghsinche opened 4 years ago

wanghsinche commented 4 years ago
def dfs(root):
  res = []
  if not root:
      return res
  if isSatisfied(root):
      res.append(root.val)
  for ele in root.children:
      left = dfs(ele)
      for i in left:
          res.append(i)
  return res
def bfs(root):
  res = []
  q = [root]
  while len(q) > 0:
    layer = q
    q = []
    for ele in layer:
         if not ele:
            continue
         if isStatified(ele):
            res.append(ele.val)
         for i in ele.children:
            q.append(i)
   return res
def bst(array):
    if len(array) <= 1:
      return isStatified(array)
    left, right = sperate(array)
    if isIn(left):
      return bst(left)
    return bst(right)
wanghsinche commented 4 years ago

To use dynamic programing to solve a problem, there are some steps we can follow with:

  1. find out the general term formula
  2. use a map or an array to store the results of sub problems
  3. iterate the problem from bottom to top, or just recurse it from the top

For example, an iterative method to solve dynamic programing problem:

cache =  dict()
def iter_dp(target):
  ## initial condition
  cache[1] = 1
  cache[2] = 2
  idx = 3
  while idx <= target:
    cache[idx] = f(cache)
  return cache[target]
wanghsinche commented 4 years ago
wanghsinche commented 4 years ago
wanghsinche commented 4 years ago

There are a nice resource. https://protegejj.gitbooks.io/my-algorithm-summary/data-structure.html

wanghsinche commented 2 years ago

https://www.techinterviewhandbook.org/ a great coding interview handbook