[LeetCode] 由 “分形" 所想
Posted 机器学习水很深
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 由 “分形" 所想相关的知识,希望对你有一定的参考价值。
分形思想和递归思想有区别么?
一、简单例子
函数调用自己,简化了理解逻辑,但其他到处都是问题。
#%% def listsum(numList): if len(numList) == 1: return numList[0] else: return numList[0] + listsum(numList[1:]) print(listsum([1,3,5,7,9]))
二、分形的思想
中文版本Tutorial: turtle
--- 海龟绘图
无限分叉树
import turtle
deftree(branchLen,t): if branchLen > 5:
# 出发后做出一系列动作,最后要回到原点 t.forward(branchLen)
t.right(20) tree(branchLen-15,t) t.left(40) tree(branchLen-15,t) t.right(20)
t.backward(branchLen) def main(): t = turtle.Turtle() myWin = turtle.Screen()
t.left(90) t.up() t.backward(100) t.down() t.color("green")
tree(100,t) myWin.exitonclick()
main()
输出:
谢尔宾斯基三角形
import turtle def drawTriangle(points,color,myTurtle): myTurtle.fillcolor(color) myTurtle.up() myTurtle.goto(points[0][0],points[0][1]) myTurtle.down() myTurtle.begin_fill() myTurtle.goto(points[1][0],points[1][1]) myTurtle.goto(points[2][0],points[2][1]) myTurtle.goto(points[0][0],points[0][1]) myTurtle.end_fill() def getMid(p1,p2): return ( (p1[0]+p2[0]) / 2, (p1[1] + p2[1]) / 2)
#########################################################################
def sierpinski(points,degree,myTurtle): colormap = [\'blue\',\'red\',\'green\',\'white\',\'yellow\', \'violet\',\'orange\'] drawTriangle(points,colormap[degree],myTurtle) if degree > 0: sierpinski([points[0], getMid(points[0], points[1]), getMid(points[0], points[2])], degree-1, myTurtle) sierpinski([points[1], getMid(points[0], points[1]), getMid(points[1], points[2])], degree-1, myTurtle ) sierpinski([points[2], getMid(points[2], points[1]), getMid(points[0], points[2])], degree-1, myTurtle) def main(): myTurtle = turtle.Turtle() myWin = turtle.Screen()
myPoints = [[-100,-50],[0,100],[100,-50]] sierpinski(myPoints,3,myTurtle)
myWin.exitonclick() main()
输出:
三、汉诺塔游戏
核心思想
要把fromPole最下面的"盘子“转移到toPole,就先要解决:
要把fromPole的height-1的"盘子“转移到withPole;在此之后:
把withPole的”盘子“也转移到toPole。
对应代码
def moveDisk(fp,tp): print("moving disk from",fp,"to",tp) def moveTower(height,fromPole, toPole, withPole): if height >= 1: moveTower(height-1,fromPole,withPole,toPole) moveDisk(fromPole,toPole) moveTower(height-1,withPole,toPole,fromPole)
模拟栈帧 之 二叉树遍历
/* implement */
以上是关于[LeetCode] 由 “分形" 所想的主要内容,如果未能解决你的问题,请参考以下文章
由 leetcode 136. Single Number 引出的异或总结