卡特兰数-生成序列

1.括号生成
左边括号=右边括号=n
每个右边括号左边至少有一个左括号

def generate(n, left=0, right=0, result=''):
  if left + right == 2 * n:
    print result
    return
  if left < n:
    generate(n, left+1, right, result+'(')
  if left > right:
    generate(n, left, right+1, result+')')
generate(3)

2.进出栈序列

def push_pop(nums, n, push=0, pop=0, stack=[],result=[]):
  if push + pop == 2*n:
    print result
    return
  if push < n:
    stack.append(nums[push])
    push_pop(nums, n, push+1, pop, stack[:], result)
    stack.pop()
  if push > pop:
    result.append(stack.pop())
    push_pop(nums, n, push, pop+1, stack[:], result)
    result.pop()
push_pop([1,2,3,4],4)

2.1-N产生的二叉搜索树

class Node:
  def __init__(self, val):
    self.val = val
    self.left = None
    self.right = None

# 遍历选取i为根,1-i-1为左子树,i+1-N为右子树,递归求解
def binary_search_tree(start, end):
  if start > end:
    return []
  roots = []
  for val in range(start, end+1):
    lefts = binary_search_tree(start, val-1)
    rights = binary_search_tree(val+1, end)
    i = 0
    j = 0
    if not lefts and not rights:
      root = Node(val)
      roots.append(root)
    while i < len(lefts) and j < len(rights):
      root = Node(val)
      root.left = lefts[i]
      root.right = rights[j]
      roots.append(root)
      i += 1
      j += 1
    while i < len(lefts):
      root = Node(val)
      root.left = lefts[i]
      root.right = None
      roots.append(root)
      i += 1
    while j < len(rights):
      root = Node(val)
      root.left = None
      root.right = rights[j]
      roots.append(root)
      j += 1
  return roots
roots = binary_search_tree(1,3)
def preOrder(root, vals=[]):
  if root:
    vals.append(root.val)
    preOrder(root.left, vals)
    preOrder(root.right, vals)
  return vals

for root in roots:
  print preOrder(root, [])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值