Leetcode Tag Search | Back

Code snippets

Category: /template

Some tricks

Template Index

Convertion

# string <--> int: 
ord('a') = 97, chr(97) = 'a'

'0'.isdecimal() == True

# enumeration:
for i in range(2**n, 2**(n+1)):
  bitmask = bin(i)[3:] # skip '0b1'
  for j in range(n):
    if bitmask[j] == '1':
      # do some actions

# K largest in heap
count = Counter(nums)
return heapq.nlargest(k, count.keys(), key=count.get)

Initialize a 2-D (M * N) array

rows = len(grid)  # M
cols = len(grid[0])  # N
dp = [[-1 for _ in range(cols)] for _ in range(rows)]

Define diagonals

Useful in checking matrix, board games.

  1. “dale” diagonals(正斜线 in math y=-x+b): in coding, row + column = const

  2. “hill” diagonals (反斜线 in math y=x+b): in coding, row - column = const

See: LC 52 N-Queens


rows = [0] * n
hills = [0] * (2 * n -1)
dales = [0] * (2 * n -1)

# place
rows[col] = 1
hills[row + col] = 1
dales[row - col] = 1

# remove
rows[col] = 0
hills[row + col] = 0
dales[row - col] = 0

# checking
return not (rows[col] or hills[row + col] or dales[row - col])

讨论

提示

  • 如果看不到讨论部分, 请暂时关掉adblock in Firefox/Chrome
  • 本网站使用Javascript实现评论功能, 此处外链对提高您的网站PR没有帮助. (潜台词: 请不要灌水, 谢谢)