递归

递归就是找递归结束的递归出口。 在此之前每算一次都调用函数,至于最终值等于什么 先不管最终值等于多少,调用函数找递归出口就完事了。

<img class=”alignnone size-full wp-image-121″ src=”

http://winston.lxyme.cn////wp-content/uploads/2021/03/图片1.png” alt=”” width=”554″ height=”406″>

两个例子均为Matlab 语言:

eg1:

递归计算阶乘:
<code>function output = fact1(n)
if n==1
output=1;
else
output=n*fact1(n-1);
end
end</code>

eg2:

汉诺塔问题:

<code>function hannuota(n,a,b,c)
if n==1
fprintf(‘把圆盘 %d 从 %c 移动到 %c \n ‘,n,a,c);%终止条件
else
hannuota(n-1,a,c,b) %把 n-1 块借助c放到b上
fprintf(“把圆盘 %d 从 %c 移动到 %c \n “,n,a,c)% 把第n个碟子从a移动到c
hannuota(n-1,b,a,c)% 把n-1个碟子借助a 从b移动到c
end
end</code>

<strong>Python:</strong>

<code>def h(n,a,b,c):
if n==1:
print(“把第{}块从{}搬到{}”.format(n,a,c))
else:
h(n-1,a,c,b) #把n-1块借助c从a搬到b
print(“把第{}块从{}搬到{}”.format(n,a,c))
h(n-1,b,a,c)#把剩下的n-1块从b借助c搬到a</code>

<img class=”alignnone size-full wp-image-124″ src=”

http://winston.lxyme.cn////wp-content/uploads/2021/03/图片2.png” alt=”” width=”660″ height=”714″>

<strong>Mathematica:</strong>

没有运行成功。

<img class=”alignnone size-full wp-image-126″ src=”

http://winston.lxyme.cn////wp-content/uploads/2021/03/Snipaste_2021-03-08_11-45-58.png” alt=”” width=”1920″ height=”2104″>

<audio style=”display: none;” controls=”controls”></audio>

<audio style=”display: none;” controls=”controls”></audio>

<audio style=”display: none;” controls=”controls”></audio>

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇