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, [])