1、汉诺塔问题:
复杂度:
f(n)=f(n-1)+1+f(n-1)
n层:2^n-1步
def func(n,fromm,to,help):
if n==1:
print("move"+" "+str(1)+" "+"from"+" "+fromm+" "+"to"+" "+to)#base case
else:
func(n-1,fromm,help,to) #将n-1层从fromm挪到help
print("move"+" "+str(n)+" "+"from"+" "+fromm+" "+"to"+" "+to) #第n层单独挪动
func(n-1,help,to,fromm) #将n-1层从help挪到
func(3,"left","right","mid")
2、打印字符串的子序列:(顺序一样,可以不连续)
def func(arr,i,pre):
if (i==len(arr)):
if pre!="":
print(pre)
return
func(arr,i+1,pre+arr[i])
func(arr,i+1,pre)
arr="abc"
arr="".join(arr)
func(arr,0,"")
3、打印字符串的全排列:(去重)
思想:
i位置把(i,n-1)位置所有字符尝试一遍(和每个位置交换),位置之后的随机排列
def printAllPermutation(arr,i):
if i==len(arr):
print((''.join(arr)))
m=[] #去重
for j in range(i,len(arr)):
if arr[